Regular expression help - comma delimited string

Viewed 66939

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?

7 Answers

Try the following expression:

/^([a-z0-9\s]+,)*([a-z0-9\s]+){1}$/i

This will work for:

  1. test
  2. test, test
  3. test123,Test 123,test

I would strongly suggest trimming the whitespaces at the beginning and end of each item in the comma-separated list.

Try ^(?!,)((, *)?([a-zA-Z0-9])\b)*$

Step by step description:

  • Don't match a beginning comma (good for the upcoming "loop").
  • Match optional comma and spaces.
  • Match characters you like.
  • The match of a word boundary make sure that a comma is necessary if more arguments are stacked in string.

Please use - ^((([a-zA-Z0-9\s]){1,45},)+([a-zA-Z0-9\s]){1,45})$

Here, I have set max word size to 45, as longest word in english is 45 characters, can be changed as per requirement

Related