Regex To Match The Last Path (Segment) Of A URL

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=&para=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=&para=123&bar=456
  • https://regexpattern.com/path/to/another/

See Also:

Regex Is Copied!