Regular expression for comma or just number

This is a bit like the previous question . Requirements have changed and I am looking for some help in coming up with a regex for a semicolon number or a number without commas. Sample input below and also some failed attempts.

Any help is appreciated.

Valid input:

1,234,567
1234567

      

Invalid input:

1234,567
1,234567

      

Some failed attempts:

^(\d{1,3}(?:[,]\d{3})*)|((\d)*)$
^\d{1,3}((?:[,]?\d{3})*|(?:[,]\d{3})*)$

      

Original success:

^\d{1,3}(?:[,]\d{3})*$

      

+2


source to share


5 answers


Just add "or one or more digits" to the end:

^(?:\d{1,3}(?:[,]\d{3})*|\d+)$

      



I think you did it almost right the first time and just didn't match all of your parentheses correctly.

+4


source


Try the following:

^\d{1,3}(?:(?:,\d{3})+|\d*)$

      



This will match any sequence starting with one to three digits followed by

  • one or more comma segments followed by three digits, or
  • zero or more digits.
+2


source


Why not use Int.TryParse () rather than regex?

+1


source


See this answer for a final discussion of "Is this a number?" the question, including accounting for correct comma separated groups of numbers.

0


source


One thing I've noticed with all of this is that the first bit of the regex allows numbers based on "0". For example, a number:

0,123,456

      

The accepted answer will match. I used:

((?<!\w)[+-]?[1-9][0-9]{,2}(?:,[0-9]{3})+)

      

It also ensures that the number has nothing in front of it. However, it does not pick up numbers less than 1000. This was done in order to prevent badly written numbers. If the final +

was ?

, the following numbers will be recorded:

0,123
1,2 (as 2 separate numbers)

      

I have a strange set of numbers to match (integers with commas, with and without spaces), so I use pretty restrictive regex to capture those groups.

Anyway, what to think about!

0


source







All Articles