0

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?

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
appix
  • 29
  • 3

1 Answers1

2

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

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
  • 1
    thank you so much, that works. I did not know there is such thing as `(?:,` earlier – appix Aug 04 '22 at 16:00
  • 1
    ++ve for nice answer. One question, can we use positive look ahead also for same? Just curious didn't try it. – RavinderSingh13 Aug 04 '22 at 16:48
  • 1
    @RavinderSingh13 If you want to match the whole string with the repeating pattern you can just match it instead. If you want to use a lookahead, you can assert the format and then match the whole string. – The fourth bird Aug 04 '22 at 17:36