Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression for numbers without leading zeros

Tags:

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]?$ 
like image 587
AGuyCalledGerald Avatar asked Oct 13 '11 12:10

AGuyCalledGerald


People also ask

How do I remove leading zeros in regex?

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.

What is difference [] and () in regex?

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.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

What does regex 0 * 1 * 0 * 1 * Mean?

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.


1 Answers

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})$ 
like image 54
Guish Avatar answered Nov 09 '22 03:11

Guish