Adam Hughes
Adam Hughes

Reputation: 16309

RegEx for example three comma-separated words

We are doing lose validation on zipcode of form CITY, ST, ZIP. These can span countries, so all of the following are valid:

All I want to validate is that we have three comma-separated words (whitespace is fine). All of these would be valid:

However these would be invalid because they don't have exactly two commas and three words:

What I've Tried Unsuccessfully

^[\w],[\w],[\w]$

^[a-zA-Z0-9_.-]*,[a-zA-Z0-9_.-]*,[a-zA-Z0-9_.-]*$  (Doesnt allow sapces)

Also just curious - do yall typically allow whitespaces in regex or prefer an application filters whitespace first and then applies the regex? We can do either.

Upvotes: 1

Views: 1967

Answers (2)

The fourth bird
The fourth bird

Reputation: 163217

The pattern ^[\w],[\w],[\w]$ that you tried, can be written as ^\w,\w,\w$ and matches 3 times a single word char with a comma in between.

The pattern ^[a-zA-Z0-9_.-]*,[a-zA-Z0-9_.-]*,[a-zA-Z0-9_.-]*$ matches 3 times repeating 0 or more times any of the listed chars/ranges in the character class with a comma in between.

As the quantifier * is 0 or more times, it could possibly also match ,,


If the word chars should be present at all 3 occasions, and there can not be spaces at the start and end:

^\w+(?:\s*,\s*\w+){2}$
  • ^ Start of string
  • \w+ Match 1+ word chars
  • (?:\s*,\s*\w+){2} Repeat 2 times matching a comma between optional whitspace chars and 1+ word chars
  • $ End of string

Regex demo

Note that \s can also match a newline. If you want to match spaces only, and the string can also start and end with a space you could use the pattern from @anubhava from the comments.

Upvotes: 2

NBekelman
NBekelman

Reputation: 13

Try ^\w*\W?,\W?\w*\W?,\W?(\w| ){1,}

(I tested by your examples)

Upvotes: 0

Related Questions