Reputation: 2741
I'm writing a method to check if input matches either
>=n, >n, <n, <=n or n..n.
Regex has always been something that's been confusing. I feel this would be a good example to understand it better.
so far I'm just checking if it has those characters
const text = '>2';
const regex = /^[<>=.0-9]|g/i;
console.log(regex.test(text));
how do I create a regex that'll only allow those specific patterns / quantifiers? eg. >5
is valid but 5>
is not.
what's the terminology behind these types of things?
Upvotes: 1
Views: 469
Reputation: 163207
You could use an alternation to match either >
or <
followed by an optional =
or match a digit followed by 2 dots.
After the alternation you could match a digit.
^(?:[<>]=?|\d\.\.)\d$
That will match:
^
Start of the string(?:
Non capturing group
[<>]=?
Match < or > or optional =|
Or\d\.\.
Match a digit and 2 dots)
Close non capturing group\d
Match a digit$
Assert the end of the stringconst strings = [
">=3",
">3",
"<2",
"<=3",
"5..5",
"5>"
];
let pattern = /^(?:[<>]=?|\d\.\.)\d$/;
strings.forEach(s => {
console.log(pattern.test(s));
});
Upvotes: 1
Reputation: 44368
You have to mind the order and be more exact:
^(?:>|<|>=|<=)(?:[1-9]\d*|0)$
(?:>|<|>=|<=)
is the set of valid operators(?:[1-9][0-9]*|0)
is the number without leading zeroSo the full regex
variable would be initialized as:
regex = /^(?:>|<|>=|<=)(?:[1-9]\d*|0)$|g/i;
You have included to match n..n
as an alternative. Here you go:
^((>|<|>=|<=)|([1-9]\d*|0)\.\.)([1-9]\d*|0)$
\.
matches the .
dot literally and must be escapedTest it:
regex = /^((>|<|>=|<=)|([1-9]\d*|0)\.\.)([1-9]\d*|0)$|g/i;
array = new Array();
array[0] = ">2"; // valid
array[1] = ">0"; // valid
array[2] = "2..3" // valid
array[3] = "=2"; // invalid
array[4] = ">01"; // invalid
array[5] = "2>"; // invalid
array.forEach(item => console.log(regex.test(item)));
If you don't mind the leading zero, simply use the:
^((>|<|>=|<=)|\d*\.\.)\d*$
Upvotes: 1