Drop04
Drop04

Reputation: 11

Regex to require space after comma in list

I want to require a space after every comma in a list. I've got this, which works pretty well for my lists that have 5 to 7 digits, separated by commas.
^([^,]{5,7},)*[^,][^ ]{5,7}$
The problem is it allows 12345,12345. I don't want that to pass. 12345, 12345 should pass. I also need just 12345 to pass, so the comma and space is not required if it's just one 5-7 digit number.

Upvotes: 0

Views: 777

Answers (2)

The fourth bird
The fourth bird

Reputation: 163577

Your regex does not match 12345,12345 because this part ([^,]{5,7},)* will match from the start including the comma.

Then it matches not a comma [^,] which will match the second 1 and then it has to match not a whitespace [^ ]{5,7} but there are only 4 characters left to match which are 2345 and it can not match.

If the first part fails it tries to match [^,][^ ]{5,7} which in total matches 6-8 characters.

You might use:

^[^,\s]{5,7}(?:, [^,\s]{5,7})*$

Regex demo

  • ^ Start of the string
  • [^,\s]{5,7} Match not a whitespace character of a comma 5 - 7 times
  • (?: Non capturing group
    • , [^,\s]{5,7} Match a comma, space and not a comma or a whitespace character 5-7 times
  • )* Close non capturing group and repeat 0+ times
  • $ End of the string

Upvotes: 1

iBug
iBug

Reputation: 37307

I didn't understand your regex, but something as simple as this should work:

^(?:\d{5,7}, )*\d{5,7}$

Or if you didn't intend to allow digit-only,

^(?:[^, ]{5,7}, )*[^, ]{5,7}$

Upvotes: 0

Related Questions