Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
721 views
in Technique[技术] by (71.8m points)

regex - How do I make this regular expression not match anything after forward slash /

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

question from:https://stackoverflow.com/questions/65934652/how-do-i-make-this-regular-expression-not-match-anything-after-forward-slash

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...