A regular expression to match the last segment (path delimited by slashes) of a URL.
/[^/]+(?=/$|$)/g
Matches:
- https://regexpattern.com/patterns/
- https://regexpattern.com/query.php?query=¶=123&bar=456
- https://regexpattern.com/path/to/another/
Sometimes, you might need to match the last segment with the last slash; use this regex instead:
/([^/]+)/?$/g
Matches:
- https://regexpattern.com/patterns/
- https://regexpattern.com/query.php?query=¶=123&bar=456
- https://regexpattern.com/path/to/another/
See Also:
- URL (With And Without Port Number) Regular Expressions
- Regex To Match One Parameter In URL Query String
- Regex To Extract Domain Name From URL
- Regular Expression To Match All URLs In Text
- Regex To Match All Parameters In A URL