I have a problem with my price regex which I'm trying to change. I want it to allow numbers like:
- 11111,64
- 2 122,00
- 123,12
- 123 345,23
For now I have something like this, but it won't accept numbers without spaces.
'^\d{1,3}( \d{3}){0,10}[,]*[.]*([0-9]{0,2'})?$'
I tried changing ( \d{3})
to (\s{0,1}\d{3})
but it still doesn't work :(
CodePudding user response:
Try this RegEx
: ^[(0-9),\s]*$
const str = '2 122,00';
console.log(/^[(0-9),\s]*$/.test(str))
CodePudding user response:
All problems are easier if you break them into pieces.
First we have to match the non decimal
1
100
1 000
10 000 000
- The first grouping is 1 to 3 digits or
\d{1,3}
- We still need to account for the following groups which may or may not be there. That in regex is a
*
or 0 or many\d{1,3}(\s\d{3})*
in that second part we put a space in front of the set to it now looks for spaces between groups of 3. - To complete this set we add in a
\d
for a flat block of numbers - Last we have to match the decimal, optionally
?
.^(\d{1,3}(\s\d{3})*|\d )(,\d )?$
/^(\d{1,3}(\s\d{3})*|\d )(,\d )?$/.test(str)
Test it some more here: https://regex101.com/r/NKAVLk/1