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
214 views
in Technique[技术] by (71.8m points)

Regex with exception inside exception

I made the following regex :

(w{2,3})(,s*w{2,3})*

It mean the sentence should start with 2 or 3 letter, 2 or 3 letter as infinite. Now i should authorise the word blue and yellow.

(w{2,3}|blue|yellow)(,s*w{2,3})*

It will works inly if blue and yellow are at the beginning

Is there a way to allow the exception's word after comma without repeting the word in the code ?


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

1 Reply

0 votes
by (71.8m points)

I'd say go with the answer given by @Toto, but if your language doesn't support recursive patterns, you could try:

^(?![, ])(?:,?s*(?:w{2,3}|blue|yellow))+$

See the online demo

  • ^ - Start string anchor.
  • (?![, ]) - Negative lookahead to prevent starting with a comma or space.
  • (?: - Open 1st non-capture group.
    • ,? - Match an optional comma, zero or more space characters and a word-boundary.
    • (?: - A nested 2nd non-capture group.
      • w{2,3}|blue|yellow - Lay our your options just once.
      • ) -Close 2nd non-capture group.
    • )+ - Close 1st non capture group and match at least once.
  • $ - End string anchor.

Just be aware that w{2,3} allows for things like __ and _1_ to be valid inputs.


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

...