简体   繁体   中英

Regex to match exactly one comma separeted strings

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

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\
\
]* - 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\
\
]*[^,\\s]+)* - 0 or more occurrences of
    • , - a comma
    • [^\\S\\n\\v\\f\\r\
\
]* - 0 or more occurrences of only horizontal whitespaces
    • [^\\s,]+ - 1 or more occurrences of characters other than whitespace and comma
  • $ - end of string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM