0

I'm looking to create a regex that would match either xxx or yyy, or any combination separated by commas.

So these would be valid:

xxx
yyy
xxx,xxx
yyy,xxx
xxx,yyy,yyy,yyy

But these would be invalid:

xx // must be exact xxx
yyyy // must be exact yyy
xxx, // trailing comma
xxxyyy // no delimiter
xxx,,yyy // should only have one comma between
,xxx,yyy // no prepending commas
zahabba
  • 2,921
  • 5
  • 20
  • 33
  • What have you tried? What didn't work? What did you get? What did you expect? What doesn't work with your code and where is it? – Toto Feb 22 '20 at 19:56

2 Answers2

1

This should suffice ^((?:xxx|yyy)(,(?:xxx|yyy))*)$. https://regex101.com/r/gT8wK5/1327

Eraklon
  • 4,206
  • 2
  • 13
  • 29
1

You can use negative lookahead like this:

^((xxx|yyy)(,(?!$)|$))+$

See it on regex101.

Compared to Eraklon's answer this regex doesn't repeat (xxx|yyy) part twice, but it's a little less performant.

TeWu
  • 5,928
  • 2
  • 22
  • 36