Prateek
Prateek

Reputation: 51

Regular Expression to get the last value in the url

I need to get the last value from the URL

Following URL scenario:

http://www.abc.com/aa/bb/cc

http://www.abc.com/aa/bb/cc?ab=1

http://www.abc.com/aa/bb/cc/

http://www.abc.com/aa/bb/cc/?ab=1

From the above URL listing i need to take out the cc from the URL Regex Expression to get value cc

Upvotes: 0

Views: 2293

Answers (1)

Joseph Silber
Joseph Silber

Reputation: 219938

This should do the trick:

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

See it here in action: http://regexr.com?322bq


Explanation:

  • ([^/?]+) - Matches any characters that are not a slash or a question mark.
  • (?= - Starts a look-ahead.
  • /? - Optionally matches a slash.
  • (?:$|\?) - Either matches a question mark, or asserts that we're at the end.
  • ) - Closes the look-ahead.

Note: In the demo, it's also matching after the ? character, since it's doing a global search. That shouldn't concern you though.

Upvotes: 2

Related Questions