Regex to match specific last path part of url

Viewed 107

For redirect purposes, I'm trying to match the last part of a path in a url. I want to match any url that ends with "/serve", whether or not a query string is present or not.

I have tried numerous Regex patterns but the following one seems to work, but it's the presence of a query string that breaks the match:

Pattern I've tried:

\/([a-z0-9_-]*\/serve[\/]?)$

Examples of test strings that should match:

https://test.com/serve
https://test.com/serve/?param=1
https://test.com/serve/
http://test.com/serve

Examples of test strings that should NOT match:

https://test.com/serve/ways-to-serve
https://test.com/serve/ways-to-serve?param=1

Thanks in advance.

1 Answers

You may use

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

See the regex demo.

Details:

  • \/ - a / char
  • ([^\/]+\/serve\/?) - Capturing group 1: one or more chars other than a / char, then a /serve, an optional / char
  • (?:$|\?) - a non-capturing group matching end of string or a ? char.

See the regex graph:

enter image description here

Related