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

后端 未结 4 1265
暖寄归人
暖寄归人 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:39

    The last slash might be optional. Right?

    How about something like this:

    $url =~ m|([^/]+)/?$|;
    my $end_of_url = $1;
    

    The $ on the end anchors the regular expression to the end of the string. The [^/] means anything that's not a slash and the + after means I want one or more things that are not slashes. Notice that this is in a capture group which are marked with parentheses.

    I end the regular expression with /? which means that there may or may not be a slash on the very end of the string. I've put my regular expression between m| and |, so I can use forward slashes without having to constantly escape them.

    The last part of the URL is now in $1 and I can set my own scalar variable to save this result.

提交回复
热议问题