Regex to match exactly one comma separeted strings

137 views Asked by At

Example:

src: anyword, anyword, anyword

I want to check if src contains only one comma separated strings like given in example

I wrote (.[^\s*]+,.*[^,\s*]+$) this but it's failing with some scenarios

For me, following scenarios are not valid

src: abc, ,1232
src: ,abc, dasf

demo: https://regex101.com/r/UyQ5KX/1

1

There are 1 answers

1
Wiktor Stribiżew On BEST ANSWER

You may use

: *[^\s,]+(?:, *[^,\s]+)*$

Or, to allow more whitespaces than just space between words:

:[^\S\n\v\f\r\u2028\u2029]*[^\s,]+(?:,[^\S\n\v\f\r\u2028\u2029]*[^,\s]+)*$

See the regex demo

If there must be 1+ non-colon chars from the start of string till the colon, you may add ^[^:]+ before the patterns above.

Details

  • ^ - start of string
  • [^:]+ - 1+ chars other than :
  • : - a colon
  • [^\S\n\v\f\r\u2028\u2029]* - 0 or more occurrences of only horizontal whitespaces
  • [^\s,]+ - 1 or more occurrences of characters other than whitespace and comma
  • (?:,[^\S\n\v\f\r\u2028\u2029]*[^,\s]+)* - 0 or more occurrences of
    • , - a comma
    • [^\S\n\v\f\r\u2028\u2029]* - 0 or more occurrences of only horizontal whitespaces
    • [^\s,]+ - 1 or more occurrences of characters other than whitespace and comma
  • $ - end of string.