I’m trying to create a regex that matches numbers greater than or equal to 150 000
, considering spaces as thousand separators. Here is the regex I tried:
^(150s*000|1[5-9]d{2}(s*d{3})*|[2-9]d{2}(s*d{3})*|d{1,2}(s*d{3})+)$
And here is the JavaScript code I used to test it:
const regex = /^(150s*000|1[5-9]d{2}(s*d{3})*|[2-9]d{2}(s*d{3})*|d{1,2}(s*d{3})+)$/;
const testStrings = [
"149 000",
"151 000",
"185 000",
"800 152",
"15 000",
"100 000",
"200 000",
"250 000 123",
"100 0000",
"150 000",
];
testStrings.forEach(testString => {
const matches = testString.match(regex);
if (matches) {
console.log(`Matched: ${testString}`);
} else {
console.log(`Did not match: ${testString}`);
}});
However, the results are not as expected:
- Did not match: 149 000
- Did not match: 151 000
- Did not match: 185 000
- Matched: 800 152
- Matched: 15 000
- Did not match: 100 000
- Matched: 200 000
- Matched: 250 000 123
- Did not match: 100 0000
- Matched: 150 000
The problem seems to be related the first part of the regex, What am I doing wrong?
I’m using a library where I have to put this regex in HTML because it is the only way to allow this condition :
<input type="radio" required name="myname" cf-label="Non" value="non" cf-conditional-price="^(150s*000|1[5-9]d{2}(s*d{3})*|[2-9]d{2}(s*d{3})*|d{1,2}(s*d{3})+)$" />
2
Answers
Why should you use regex?
We can approach this by converting the string values to numeric values first.
Here is a regex that seems to work with your criteria of any number >= 150,000 with spaces replacing the commas:
Now I would highly recommend some alternative routes as suggested in the comments, but if you really have to use a regex, this one seems to work fine. Hope this helps!
Here is the finished code replacing your regex: