Regex – Regular expression help – comma delimited string

regexvb.net

I don't write many regular expressions so I'm going to need some help on the one.

I need a regular expression that can validate that a string is an alphanumeric comma delimited string.

Examples:

  • 123, 4A67, GGG, 767 would be valid.
  • 12333, 78787&*, GH778 would be invalid
  • fghkjhfdg8797< would be invalid

This is what I have so far, but isn't quite right: ^(?=.*[a-zA-Z0-9][,]).*$

Any suggestions?

Best Answer

Sounds like you need an expression like this:

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

Posix allows for the more self-descriptive version:

[[:alnum:]]+(,[[:alnum:]]+)*
[[:alnum:]]+([[:space:]]*,[[:space:]]*[[:alnum:]]+)*  // allow whitespace

If you're willing to admit underscores, too, search for entire words (\w+):

\w+(,\w+)*
\w+(\s*,\s*\w+)*  // allow whitespaces around the comma

(Thanks to Alan for pointing out several of my failings!)