1

I have this regular expression:

/^www\.example\.(com|co(\.(in|uk))?|net|us|me)\/?(.*)?[^\/]$/g

It matches:

www.example.com/example1/something

But doesn't match

www.example.com/example1/something/

But the problem is that, it matches: I do not want it to match:

www.example.com/example1/something/otherstuff

I just want it to stop when a slash is enountered after "something". If there is no slash after "something", it should continue matching any character, except line breaks.

I am a new learner for regex. So, I get confused easily with those characters

Example person
  • 3,198
  • 3
  • 18
  • 45

2 Answers2

2

You may use this regex:

^www\.example\.(?:com|co(?:\.(?:in|uk))?|net|us|me)(?:\/[^\/]+){2}$

RegEx Demo

This will match following URL:

www.example.co.uk/example1/something
anubhava
  • 761,203
  • 64
  • 569
  • 643
1

You can use

^www\.example\.(?:com|co(?:\.(?:in|uk))?|net|us|me)\/([^\/]+)\/([^\/]+)$

See the regex demo

The (.*)? part in your pattern matches any zero or more chars, so it won't stop even after encountering two slashes. The \/([^\/]+)\/([^\/]+) part in the new pattern will match two parts after slash, and capture each part into a separate group (in case you need to access those values).

Details:

  • ^ - start of string
  • www\.example\. - www.example. string
  • (?:com|co(?:\.(?:in|uk))?|net|us|me) - com, co.in, co.uk, co, net, us, me strings
  • \/ - a / char
  • ([^\/]+) - Group 1: one or more chars other than /
  • \/ - a / char
  • ([^\/]+) - Group 2: one or more chars other than /
  • $ - end of string.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563