How do I get the last segment of URL using regular expressions

后端 未结 4 1266
暖寄归人
暖寄归人 2020-12-31 07:06

I have a URL:

www.domain.com/first/second/last/

How do I get the last term between slashes? i.e. last using regular expressions?

4条回答
  •  攒了一身酷
    2020-12-31 07:32

    This should do the trick:

    [^/]+(?=/$|$)
    

    With a (?=lookahead) you won't get the last slash.

    [^/]+ Looks for at least one character that is not a slash (as many as possible). (?=/?^|^) makes sure that the next part of the string is a / and then the end of string or just end of string.

    Matches match in /one/two/match, '/one/two/match/'.

提交回复
热议问题