简体   繁体   中英

Using Regex to extract word

I have a pattern as follows:

document_data/Filename.xyz

I'm trying to write a regular expression that will only return "Filename". I have one that gives me just "xyz" and it works, and I have one that gives me "Filename.xyz" but I"m having trouble chopping off the xyz to just get Filename.

[^/]+$ gives me "Filename.xyz" \\[^.]+$ gives me xyz

I'm not a regex person so any help would be great! Thanks!

try to use a lookahead (?=...) :

/[^\/.]+(?=\.[^.]+$)/

A lookahead performs only a check and means followed by but match nothing.

将两者结合起来,并将第一部分包装在一个捕获组中:

"document_data/Filename.xyz".match(/([^/]+)\.[^.]+$/)[1]

I hope its could help (cf: http://planetozh.com/blog/2008/04/javascript-basename-and-dirname/ )

    function basename(path) {
        return path.replace(/\\/g,'/').replace( /.*\//, '' ).replace( /\..*/, '' );
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM