I need to check whether a string is valid price or not. In some locales, "." is interchanged with "," and separator could be at thousands or hundreds. For Example: Valid:
1234
1,234
1.234
1,23,334
1.23.334
1,23,334.00
1.23.334,00
Invalid:
1,23...233
1,,23
etc
The Regex I have used is
/(\d+(?:[\.,](?![\.,])\d+)*)/g
but this is giving me two matches for "1,23...233" i,e "1,23" and "233" as matches, I don't want to return any matches for that. Here is the regex I have been working on. What I actually want to do, whenever there is "." or "," next character should not be "." or "," and it should be a digit.
I need to check whether a string is valid price or not. In some locales, "." is interchanged with "," and separator could be at thousands or hundreds. For Example: Valid:
1234
1,234
1.234
1,23,334
1.23.334
1,23,334.00
1.23.334,00
Invalid:
1,23...233
1,,23
etc
The Regex I have used is
/(\d+(?:[\.,](?![\.,])\d+)*)/g
but this is giving me two matches for "1,23...233" i,e "1,23" and "233" as matches, I don't want to return any matches for that. Here is the regex I have been working on. What I actually want to do, whenever there is "." or "," next character should not be "." or "," and it should be a digit.
Share Improve this question asked Jan 21, 2015 at 6:51 saiki4116saiki4116 3231 gold badge4 silver badges14 bronze badges 3-
Seems to me
!/\.\.|,,/.test(string)
should do the job. If you also want to check that everything else is a digit, then:!/\.\.|,,|\D/.test(string)
. The expressions return false if any of the patterns is found, otherwise true. – RobG Commented Jan 21, 2015 at 7:07 - You should use plugin here instead of the Regex. – Naveen Chandra Tiwari Commented Jan 21, 2015 at 7:20
- @anubhava , That seems fine for checking. What if we need to pick the price from, let's say "123,456.00 USD" – saiki4116 Commented Jan 21, 2015 at 7:29
2 Answers
Reset to default 3You can simply do this.
^\d+(?:[.,]\d+)*$
Try this.See demo.
https://regex101./r/tX2bH4/61
var re = /^\d+(?:[.,]\d+)*$/gm;
var str = '1234\n1,234\n1.234\n1,23,334\n1.23.334\n1,23,334.00\n1.23.334,00\n1,23...233\n1,23.';
var m;
while ((m = re.exec(str)) != null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
Seems like you want something like this,
^\d+(?:\.\d+)?(?:,\d+(?:\.\d+)?)*$
DEMO
OR
^(?!.*(,,|,\.|\.,|\.\.))[\d.,]+$
Negative lookahead at the start asserts that the sting won't contain consecutive mas or dots or dots and mas.
DEMO