Home > other >  Regex for numeric value that could contain comma & dots
Regex for numeric value that could contain comma & dots

Time:09-17

I have been trying but without success I need a regular expression for validating numbers that could contain dots and commas, the number should be positive and there should be max of two numbers after the comma

Valid cases would be:

1000 - valid
1,000 - valid
1,000.22 - valid


-2 not valid
1,000.233 not valid
0 not valid
1.00,22 - not valid

Language is javascript

CodePudding user response:

let valid =["1000","1,000","1,000.22"];
let notValid = ["-2","1,000.233 ","0","1.00,22"];

let rge = /^[1-9] \d*(,\d{3})*(\.\d{1,2})?$/;

for(let x of valid)
  console.log(x," è valida? ",rge.test(x));
  
for(let x of notValid)
  console.log(x," è valida? ",rge.test(x));
  

Above there is a possible solution in Javascript, you haven't specified the language. \d are numbers in the range [0-9]
The full stop . is a metacharacter (it means any character), to refer to the character . you have to escape it thereby \.

means at least 1 or more times

* means 0 or more times

? means 0 or 1 time

{1,2} means match minimum 1 time, maximum 2 times

The starting ^ and final $ refer to a exact matching otherwise you could have a partial matching of the string

CodePudding user response:

A few assumptions:

  • Invalid: '123456789.12' and '12345,123.12'

I think the following does what you are after:

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

See the online demo

  • ^ - Start-line anchor.
  • [1-9] - A single digit in the range 1-9.
  • (?: - Open a non-capture group:
    • \d* - 0 Digits to allow any integer.
    • | - Or:
    • \d{0,2} - Between 0 to 2 digits;
    • (?:,\d{3})* - Followed by a non-capture group to allow any 0 times a comma followed by 3 digits.
    • (?:\.\d\d?)? - Followed by an optional non-capture group to allow up to two decimals.
    • )$ - Close non-capture group and match the end-line anchor.

Or, if you also want to allow any integer followed by decimals (e.g: '123456789.01') you may change this to:

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

CodePudding user response:

I think this regex should do the trick:

[1-9][\d,]*(\.\d{1,2})?

[1-9] - matches one character between 1 and 9 at the beginning (required to not match 0)

[\d,]* - matches zero or more digits or commas

(\.\d{1,2})? - zero or one group of a dot and one or two digits

For testing regexes I do recommend https://regex101.com/

  • Related