Home > Enterprise >  Regex pattern matching comma delimited values with spaces allowed around comma
Regex pattern matching comma delimited values with spaces allowed around comma

Time:08-16

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).

CodePudding user response:

\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
  • Related