Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression help - comma delimited string

Tags:

regex

vb.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?

like image 325
John H. Avatar asked Jun 23 '11 02:06

John H.


People also ask

How do you match a comma in regex?

The 0-9 indicates characters 0 through 9, the comma , indicates comma, and the semicolon indicates a ; . The closing ] indicates the end of the character set. The plus + indicates that one or more of the "previous item" must be present.

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.

How split a string in regex?

To split a string by a regular expression, pass a regex as a parameter to the split() method, e.g. str. split(/[,. \s]/) . The split method takes a string or regular expression and splits the string based on the provided separator, into an array of substrings.

What does \s mean in regex?

\s stands for “whitespace character”. Again, which characters this actually includes, depends on the regex flavor. In all flavors discussed in this tutorial, it includes [ \t\r\n\f]. That is: \s matches a space, a tab, a carriage return, a line feed, or a form feed.


1 Answers

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
like image 176
Kerrek SB Avatar answered Oct 19 '22 11:10

Kerrek SB