I have a regex
/([/<=][^/]*[/=?])$/g
I'm trying to capture text between the last slashes in a file path
/1/2/test/
but this regex matches " /test/
" instead of just test
. What am I doing wrong?
You need to use lookaround assertions.
(?<=\/)[^\/]*(?=\/[^\/]*$)
or
Use the below regex and then grab the string you want from group index 1.
\/([^\/]*)\/[^\/]*$
The issue with your code is your opening and closing slashes are part of your capture group.
/1/2/test/
/\\/(\\[^\\/\\]*?)(?=\\/)/g
/
match characters must be escaped (according to regex101.com), which is why the cleaner [/]
wasn't used. If you're only after the last match (ie, test
), you don't need the positive lookahead:
/\/([^\/]*?)\/$/
Match:
/
"
/
" and then the end of string $
Code:
([^/]*)/$
Get the text in group(1)
Match exactly the same as before, except now we're telling the regex engine not to consume characters when trying to match (2). This is done with a lookahead : (?= )
.
Code:
[^/]*(?=/$)
Get what is returned by the match object.
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.