简体   繁体   中英

Regex pattern matching comma delimited values with spaces allowed around comma

I am trying to write a Regex validator (Python 3.8) to accept strings like these:

foo
foo,bar
foo, bar
foo , bar
foo    ,      bar
foo, bar,foobar

This is what I have so far (but it matches only the first two cases):

^[a-zA-Z][0-9a-zA-Z]+(,[a-zA-Z][0-9a-zA-Z]+)*$|^[a-zA-Z][0-9a-zA-Z]+

However, when I add the whitespace match \w , it stops matching altogether:

^[a-zA-Z][0-9a-zA-Z]+(\w+,\w+[a-zA-Z][0-9a-zA-Z]+)*$|^[a-zA-Z][0-9a-zA-Z]+

What is the pattern to use (with explanation as to why my second pattern above is not matching).

\w matches [0-9a-zA-Z_] and it doesn't include whitespaces.

What you need is this regex:

^[a-zA-Z][0-9a-zA-Z]*(?:\s*,\s*[a-zA-Z][0-9a-zA-Z]*)*$

RegEx Demo

RegEx Details:

  • ^ : Start
  • [a-zA-Z][0-9a-zA-Z]* : Match a text starting with a letter followed by 0 or more alphanumeric characters
  • (?: : Start non-capture group
    • \s*,\s* : Match a comma optionally surrounded with 0 or more whitespaces on both sides
    • [a-zA-Z][0-9a-zA-Z]* : Match a text starting with a letter followed by 0 or more alphanumeric characters
  • )* : End non-capture group. Repeat this group 0 or more times
  • $ : End

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