skip to Main Content

Hi i need to create regex that will match numbers in range -1 to 1, chat got problem with that and also i didnt find many answers, now im stuck because my regex match also -1.5 and 1.5 value but it should, my current regex is: ^-?1(.0+)?|^-?0(.[0]+)?$

2

Answers


  1. Try this: ^-?1(.0+)?|^-?0(.[0-9]+)?$

    Explanation:

    • ^ asserts the start of the string.

    • -? matches an optional minus sign.
      1(.0+)? matches the number 1 followed by an optional decimal point and one or more zeros.

    • | is the alternation operator, allowing matching either the previous pattern or the next pattern.

    • ^-?0(.[0-9]+)?$ matches the number 0 or a decimal number between -1 and 1.

    Examples of matching numbers using this regex:

    -1

    -0.5

    0

    0.5

    1

    Examples of non-matching numbers:

    -1.5

    1.5

    -2

    2

    Login or Signup to reply.
  2. Try it the following way:

    ^-?0*(?:0(?:.[0-9]*)?|1(?:.0*)?)$
    

    Here’s a small explanation for you:

    ^ and $ asserts the start and end of the string

    -? matches an optional minus sign.

    0* matches one zero sign or any other

    (?:0(?:.[0-9]*)?|1(?:.0*)?) :

    0(?:.[0-9]*)?: matches a zero sign that is followed by an optional decimal point and one or more zero digits

    1(?:.0*)?: matches one followed by an optional decimal point and zero or more trailing zeros.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search