How to validate the last character in a capture group with regex

Viewed 237

I want to extract the path out of a URL and I want to use regex for it.

I'm using this regex: ^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:\n\?\=ֿ\#]+)

and one side effect that the last / is captured.

e.g. -

domain.com/home/ = domain.com/home/
domain.com/home?param=value = domain.com/home

how do I validate that the last character of a specific capture group is not /?

note - I know I can solve this with another regex match, but I assume it can be done with one.

2 Answers

One way could be adding the / to the negated character class to not match it, and only match it when it is followed by any char other than / or a whitespace char.

^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?((?:[^:\n?=ֿ#\/]+|\/(?=[^\s\/])[^:\n?=ֿ#\/]*)*)

The last part will match

  • ( Capture group 1
    • (?: Non capture group
      • [^:\n?=ֿ#\/]+ Match any char except the listed including /
      • | Or
      • \/(?=[^\s\/]) match / when directly followed by any char other then / or a whitespace char
      • [^:\n?=ֿ#\/]* Match optional chars other than the listed
    • )* Close non capture group and repeat 0+ times to match multiple /
  • ) Close group 1

Regex demo

You can make your last match non-greedy followed by an optional /. Then make sure that is followed by a ? or end:

^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:\n?=ֿ#]+?)\/?(?=\?|$)

RegEx Demo

Your group #1 will stop a position before last / assuming URL ends with that or there is a query string afterwards.

Related