GigiProve
GigiProve

Reputation: 337

Regex for numbers, commas and whitespaces

I need a RegEx that allow the strings that start with numbers separated by comma, finishes with a number (or withspaces after the number) and allow also whitespaces between the number and the comma. E.g. var str= '1 , 8,9, 88' has to be accetpted while var str2="1 2, 5" has not to be accetped. I tried with var regEx= "^[0-9\,\s]+$"but doing like this it accepts the strings that end with a comma and the strings that have two numbers not separated by comma. Any ideas?

EDIT:

Example of string accepted:

str1= "1,2,3,4"
str2= "1 , 2,3,9"
str3= "  8 , 44, 3  , 11"

Example of string to be discarded:

str4="1, 2,"
str5=", 1,2,"
str6="1,2 3,4"

Upvotes: 3

Views: 1809

Answers (1)

The fourth bird
The fourth bird

Reputation: 163207

You could account for the spaces before and after the comma using \s (or just match a space only because \s also matches a newline) to match a whitespace character and use a repeating pattern to match a comma and 1+ digits:

^\s*\d+(?:\s*,\s*\d+)*\s*$
  • ^ Start of string
  • \s*\d+ Match 0+ whitespace chars and 1+ digits
  • (?: Non capturing group
    • \s*,\s*\d+ Match 0+ whitespace chars, and comma, 0+ whitespace chars and 1+ digits
  • )* Close non capturing group and repeat 0+ times
  • \s*$ Match 1+ whitespace chars and assert end of string.

Regex demo

Upvotes: 3

Related Questions