Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...