I need a regular expression to match any number from 0 to 99. Leading zeros may not be included, this means that f.ex. 05 is not allowed.
I know how to match 1-99, but do not get the 0 included.
My regular expression for 1-99 is
^[1-9][0-9]?$
Use the inbuilt replaceAll() method of the String class which accepts two parameters, a Regular Expression, and a Replacement String. To remove the leading zeros, pass a Regex as the first parameter and empty string as the second parameter. This method replaces the matched value with the given string.
This answer is not useful. Show activity on this post. [] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.
$ means "Match the end of the string" (the position after the last character in the string).
Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.
There are plenty of ways to do it but here is an alternative to allow any number length without leading zeros
0-99:
^(0|[1-9][0-9]{0,1})$
0-999 (just increase {0,2}):
^(0|[1-9][0-9]{0,2})$
1-99:
^([1-9][0-9]{0,1})$
1-100:
^([1-9][0-9]{0,1}|100)$
Any number in the world
^(0|[1-9][0-9]*)$
12 to 999
^(1[2-9]|[2-9][0-9]{1}|[1-9][0-9]{2})$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With