Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
881 views
in Technique[技术] by (71.8m points)

regex - Regular expression for numbers without leading zeros

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]?$
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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})$

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...