Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

Please note that the URL could just be:

www.domain.com/last/ 

Or:

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

I need to extract this last term for use in the Zeus Server's Request Rewrite module which uses PERL and REGEX.

Update

After implementing some answers, I have just realized that I need this match to be made only on URLs in a certain directory.

i.e.

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

should return last. Whereas:

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

should not return a match.

like image 875
Matt Avatar asked Jan 10 '12 03:01

Matt


People also ask

How do you specify the end of a line in RegEx?

End of String or Line: $ The $ anchor specifies that the preceding pattern must occur at the end of the input string, or before \n at the end of the input string. If you use $ with the RegexOptions. Multiline option, the match can also occur at the end of a line.

What is URL RegEx?

URL regular expressions can be used to verify if a string has a valid URL format as well as to extract an URL from a string.


3 Answers

Here's a simple regex:

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

Should match anything you throw at it.


If you want to look in a particular directory, use this:

/directory.*/([^/]+)/?$

and your result will be in the first capture group.

like image 136
Joseph Silber Avatar answered Oct 16 '22 20:10

Joseph Silber


This regex (a slightly modified version of Joseph's answer), should give you the last segment, minus ending slash.

([^/]+)/?$

Your result will be the first capture group.

like image 31
Adam Wagner Avatar answered Oct 16 '22 19:10

Adam Wagner


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/'.

like image 3
agent-j Avatar answered Oct 16 '22 19:10

agent-j