简体   繁体   中英

Trying to figure out how to capture text between slashes regex

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.

(?<=\/)[^\/]*(?=\/[^\/]*$)

DEMO

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.

Demo

  • text: /1/2/test/
  • regex: /\\/(\\[^\\/\\]*?)(?=\\/)/g
  • captures a list of three: "1", "2", "test"
  • The language you're using affects the results. For instance, JavaScript might not have certain lookarounds, or may actually capture something in a non-capture group. However, the above should work as intended. In PHP, all / 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:

/\/([^\/]*?)\/$/

The easy way

Match:

  1. every character that is not a " / "
    • Get what was matched here. This is done by creating a backreference , ie: put inside parenthesis.
  2. followed by " / " and then the end of string $

Code:

([^/]*)/$

Get the text in group(1)


Harder to read, only if you want to avoid groups

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.

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