Anton Hughes
Anton Hughes

Reputation: 1995

RegEx that detects space between numbers but space between commas are ok

I am using angularjs and curently have the following REGEX

ng-pattern = "/^[0-9,\b\s]+$/"

This regex works to a degree although I am unable to find how to alter it to detect white space between numbers, but at the same time allow white space between commas.

ie

123                     // is ok
123,  345,   5453       // is ok
123   345,   5453       // is not ok
123,   345,   5453,     // is not ok
,123,   345,   5453     // is not ok

Any ideas?

Upvotes: 1

Views: 894

Answers (3)

anubhava
anubhava

Reputation: 785128

You can use this regex:

^(?:\d+(?:, *|))*\d+$

Online Regex Demo

Upvotes: 1

Nicholas Carey
Nicholas Carey

Reputation: 74257

This regular expression

^\d{1,3}(,\s*\d\d\d)*$

Matches

  • start-of-text, followed by
  • a group of 1-3 digits, followed by
  • zero or more groups, each consisting of
    • a comma, followed by
    • optional whitespace, followed by
    • a group of 3 digits -followed by end-of-text

Which is to say...any number written in the conventional group-delimited form using commas as the group delimiter and allowing trailing whitespace following the commas:

1
12
123
1,234
12, 123,456

All match, but things like

123456
123,4
1 234

If you wanted to make the group separators optional, it's an easy modification:

^\d{1,3}((,\s*)?\d\d\d)*$

This will also match numbers like

12345
12, 3456

Etc.

Upvotes: 1

Federico Piazza
Federico Piazza

Reputation: 30995

You can use this regex:

^(?:\d+,\s*)+\d+$

http://regex101.com/r/xE2sQ3/1

123,  345,   5453    // OK
123   345,   5453
123,  345,   5453    // OK
123,  345   5453,

Upvotes: 1

Related Questions