Search code examples
regexregular-language

Regular expression for integer with or without commas


I want to create a regular expression for all sorts of numbers i.e whole numbers (+ve and -ve) and decimal numbers (+ve and -ve) with or without commas.

For e.g the regular expression should cover following number formats.

  111     1.11     1,111     1,111.01     1,111,111.01 
 +111    +1.11    +1,111    +1,111.01    +1,111,111.01
 -111    -1.11    -1,111    -1,111.01    -1,111,111.01

I have created two regular expressions for handling my scenario.

 "^(\\+|-)?[0-9]\\d*(\\.\\d+)?$"   // handles whole numbers with decimals
 "^(\\+|-)?[0-9]\\d*(\\,\\d+)*?$"  // handles whole numbers with commas

Now, I want to merge these two regular expressions in order to address my requirements.

Can anyone help me?
Thanks in advance.


Solution

  • You may merge these 2 patterns of yours like

    ^[+-]?[0-9]+(?:,[0-9]+)*(?:[.][0-9]+)?$
    

    See the regex demo

    Details:

    • ^ - start of a string
    • [+-]? - an optional + or -
    • [0-9]+ - 1 or more digits
    • (?:,[0-9]+)* - zero or more sequences of:
      • , - a comma
      • [0-9]+ - 1 or more digits
    • (?:[.][0-9]+)? - an optional sequence of:
      • [.] - a dot
      • [0-9]+ - 1+ digits
    • $ - end of string

    A more restrictive regex to only allow 3-digits in groupings will look like

    ^[+-]?[0-9]{1,3}(?:,[0-9]{3})*(?:[.][0-9]+)?$
               ^^^^^         ^^^
    

    And if you want to also match whole parts with no thousand separators:

    ^[+-]?(?:[0-9]{1,3}(?:,[0-9]{3})*|[0-9]+)(?:[.][0-9]+)?$