0

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 ?

3
  • Depending on language you are using, you can use recursive pattern. Commented Jan 6, 2021 at 12:35
  • Add sentence examples that your regex should be able to understand. Commented Jan 6, 2021 at 12:37
  • Is that what you want? Commented Jan 6, 2021 at 12:39

3 Answers 3

2

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

^(?![, ])(?:,?\s*\b(?:\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.
    • ,?\b - 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.

Sign up to request clarification or add additional context in comments.

Comments

1

If the language you are using supports recursive patterns, you can use:

^(blue|yellow|\w{2,3})(?:,\s*(?1))*$

Demo & explanation

Comments

1

If either blue or yellow can occur only once:

^(?:\w{2,3}\s*,\s*)*(?:blue|yellow)(?:\s*,\s*\w{2,3})*$

The pattern matches

  • ^ Start of string
  • (?:\w{2,3}\s*,\s*)* Optionally repeat 2-3 word chars followed by a comma
  • (?:blue|yellow) Match either blue or yellow
  • (?:\s*,\s*\w{2,3})* Optionally match a comma and 2-3 word chars
  • $ End of string

Regex demo

2 Comments

Yeah, I was thinking if we should take "Is there a way to allow the exception's word after comma without repeting the word in the code ?" as in allowing the word just once or creating the pattern with mentioning the word just once. Either way, kudos =)
@JvdV Hmm..reading it again I might be wrong. Maybe it should be optional just allowing blue or yellow in the sequence.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.