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:
^(150\s*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 = /^(150\s*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:
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="^(150\s*000|1[5-9]\d{2}(\s*\d{3})*|[2-9]\d{2}(\s*\d{3})*|\d{1,2}(\s*\d{3})+)$" />
Here is a regex that seems to work with your criteria of any number >= 150,000 with spaces replacing the commas:
/\b((1[5-9]\d|[2-9]\d{2}|\d{4,})(\s\d{3})+)\b/
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:
const regex = /\b((1[5-9]\d|[2-9]\d{2}|\d{4,})(\s\d{3})+)\b/;
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}`);
}
});