Regexp for a European price

I checked the following regexp for US prices (separating comma, separating dot), which works fine:

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

It works, prices such as 30,000,000 are rejected. Only 2 decimal places are accepted.

I tried to exchange them to handle European prices:

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

but this does not work, prices such as 30,000,000 are accepted, which is not true. Only 2 decimal places should be accepted.

What is wrong with these two regular expressions?

+4
source share
1 answer

In regular expression . is a special character, so when you want to combine a literal dot, you need to avoid it with a backslash ( \. ). This does not apply to commas, so you can leave them unchanged.

In your attempt, you switched , and . that left you unselected . and a \, at the end, when you really want to change , and \. eg:

 ^[1-9][0-9]{0,2}(?:\.?[0-9]{3}){0,3}(,[0-9]{2})?$ 
+5
source

Source: https://habr.com/ru/post/1397897/


All Articles