1

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?

1
  • You can use: /^[<>]=?\d+\.?\d*$/ Commented Nov 28, 2018 at 21:18

3 Answers 3

1

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 zero

So 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 escaped

Test 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*$
Sign up to request clarification or add additional context in comments.

1 Comment

how about for n..n?
1

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 string

Regex demo

const strings = [
  ">=3",
  ">3",
  "<2",
  "<=3",
  "5..5",
  "5>"
];
let pattern = /^(?:[<>]=?|\d\.\.)\d$/;
strings.forEach(s => {
  console.log(pattern.test(s));
});

Comments

0

You can probably use ^[<>]=?\d+$

  • ^ match from the beginning of the string
  • [<>] mandatory greater or less mark
  • =? optional equal mark
  • \d+ any number of digits
  • $ match till the end of the string

Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.