appix
appix

Reputation: 29

Regex for repeated pattern separated by comma

Hey so I would like to generate a regex that repeats a pattern (\w*:\w*) separated by a comma. I will include some valid and invalid patterns to see in the following:

Valid: SomeAlpha:Abc
Valid: Aa:Bb,Cc:Dd,Ee:Ff,Gg:Hh
Invalid: Aa:Bb,Cc:Dd,Ee:Ff,
Invalid: First:oNe:NoComma

I currently setup the regex like this

\(\w*:\w*,\)*

However, as you can see the issue is that the pattern has to end with the comma. I tried putting ?, but it does not validate the fourth example in the above. Is there any pattern expression that I could do in the case?

Upvotes: 0

Views: 601

Answers (1)

The fourth bird
The fourth bird

Reputation: 163362

You could write the pattern as:

^\w+:\w+(?:,\w+:\w+)*$

Explanation

  • ^ Start of string
  • \w+:\w+ Match : between 1+ word chars
  • (?:,\w+:\w+)* Optionally repeat the comma and the previous pattern using a non capture group (?:
  • $ End of string

Regex demo

Upvotes: 2

Related Questions