Regexes for validating & formatting numbers with different decimal delimiters

66 views Asked by At

I'm trying to construct a regex to validate and capture numbers that can have either a comma or a dot as delimiter. After validation i want to output the formatted number using substitution.

This is my input and desired output (or at least enough to show my case):

,1 -> no match  
.1 -> no match  
1   -> 1  
10   -> 10  
10,5 -> 10,5  
333,5 -> no match  
5,555 -> no match  
10.50 -> 10,50  ( optimal output would be: 10,5 but not a requirement )  
blabla 10.5 blabla -> 1,5

with a maximum of 2 digits on both sides of the delimiter..

I use the following regex for validation:

^.*(?<!\S)(\d{1,2})(?:([\,\.])(\d{1,2}))?(?!\S).*$

the substitution regex below obviously doesn't work since numbers with no decimals would be wrong..

${number},${decimals}

can it be done with only 1 test & 1 substitution regex ? i guess the whole thing needs a redo.. but how ? :)

1

There are 1 answers

6
Michel Antoine On

Here is what you could do:

(?<![\d,.])(\d{1,2})(?:[.,](\d{1,2}))?(?![\d,.])

Example

Explanation:

  1. (?<![\d,.]): Should not be preceded by a number or a delimiter (EG: ',' or '.')
  2. (\d{1,2}): One to two digits
  3. (?:[.,](\d{1,2}))?: If there is a delimiter (EG: ',' or '.') there should be at least one to two digits after it
  4. (?![\d,.]): Should not be followed by a digit or a delimiter (EG: ',' or '.')

Edit: I added the capturing groups. You will be able to get the number with the first match and the floating value with the second.

UPDATE: Dots are not escaped in a character classes anymore. (Thanks to @Tensibai)