0

Need regex for following combination.

  • Only Numbers

  • Max 2 digit after decimal

  • following types of range available

    • 5
    • 8.95
    • >2.5
    • <5.65
    • >=4.24
    • <=7.2
    • 1.2-3.2

i tried below regex which accept number, two decimal no and should not end with <>=. special characters.

/^(?!.*<>=.$)[0-9]+(\.[0-9]{1,2})?$/gm

Need regex for range values

5
  • i have added more explanation and what i have tried. Commented Feb 15, 2021 at 9:06
  • Can you have >=4.24-3.2? Commented Feb 15, 2021 at 9:07
  • >=4.24 - 3.2 No we cant have. Commented Feb 15, 2021 at 9:07
  • 1
    Perhaps like ^(?:(?:[<>]=?)?\d+(?:\.\d{1,2})?|\d+(?:\.\d{1,2})?-\d+(?:\.\d{1,2})?)$ regex101.com/r/6bzGE9/1 Commented Feb 15, 2021 at 9:09
  • 1
    this is ^(?:(?:[<>]=?)?\d+(?:\.\d{1,2})?|\d+(?:\.\d{1,2})?-\d+(?:\.\d{1,2})?)$ working as expected. Thanks alot. Commented Feb 15, 2021 at 9:16

2 Answers 2

1

You could match either a single occurrence of a number preceded by a combination of <>= or match 2 numbers with a hyphen in between.

^(?:(?:[<>]=?)?\d+(?:\.\d{1,2})?|\d+(?:\.\d{1,2})?-\d+(?:\.\d{1,2})?)$
  • ^ Start of string
  • (?: Non capture group for the alternation
    • (?:[<>]=?)? Optionally match < > <= >=
    • \d+(?:\.\d{1,2})? Match 1+ digits with optional decimal part of 1-2 digits
    • | Or
    • \d+(?:\.\d{1,2})?-\d+(?:\.\d{1,2})? Match a digits format with a hyphen in between
  • ) Close group
  • $ End of string

See a regex demo

const pattern = /^(?:(?:[<>]=?)?\d+(?:\.\d{1,2})?|\d+(?:\.\d{1,2})?-\d+(?:\.\d{1,2})?)$/;
[
  "5",
  "8.95",
  ">2.5",
  "<5.65",
  ">=4.24",
  "<=7.2",
  "1.2-3.2",
  "1-1.3",
  "1-4",
  ">2",
  ">=4",
  "2.5>",
  "1.123"
].forEach(s => console.log(`${s} ==> ${pattern.test(s)}`));

Sign up to request clarification or add additional context in comments.

Comments

1

This regex does what you ask for. The test has first some matches, followed by non-matches:

const regex = /^(([><]=?)?[0-9]+(\.[0-9]{1,2})?|[0-9]+(\.[0-9]{1,2})?-[0-9]+(\.[0-9]{1,2})?)$/;
[
  '1',
  '12',
  '12.2',
  '12.34',
  '>1.2',
  '>=1.2',
  '<1.2',
  '<=1.2',
  '1.2-3.4',
  '1.22-3.44',
  'x1',
  '1.234',
  '1.222-3.444'
].forEach((str) => {
  let result = regex.test(str);
  console.log(str + ' ==> ' + result)
})

Output:

1 ==> true
12 ==> true
12.2 ==> true
12.34 ==> true
>1.2 ==> true
>=1.2 ==> true
<1.2 ==> true
<=1.2 ==> true
1.2-3.4 ==> true
1.22-3.44 ==> true
x1 ==> false
1.234 ==> false
1.222-3.444 ==> false

1 Comment

@Roshan Patil: Any questions? Does this fit your needs?

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.