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]+)?$
Question posted in Javascript
A very good W3school tutorial can be found here.
A very good W3school tutorial can be found here.
2
Answers
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
Try it the following way:
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 digits1(?:.0*)?
: matches one followed by an optional decimal point and zero or more trailing zeros.