开发者

Regular expression for numbers without leading zeros

开发者 https://www.devze.com 2023-04-12 23:04 出处:网络
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 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开发者_如何学Python expression for 1-99 is

^[1-9][0-9]?$


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


Updated:

^([0-9]|[1-9][0-9])$

Matches 0-99. Doesn't match values with leading zeros. Depending on your application you may need to escape the parentheses and the or symbol.


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

Test here http://regexr.com?2uu31 (various samples included)

You have to add a 0|, but be aware that the "or" (|) in Regexes has the lowest precedence. ^0|[1-9][0-9]?$ in reality means (^0)|([1-9][0-9]?$) (we will ignore that now there are two capturing groups). So it means "the string begins with 0" OR "the string ends with [1-9][0-9]?". An alternative to using brackets is to repeat the ^$, like ^0$|^[1-9][0-9]?$.


[...] but do not get the 0 included.

Just add 0|... in front of the expression:

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


console.log(/^0(?! \d+$)/.test('0123')); // true
console.log(/^0(?! \d+$)/.test('10123')); // false
console.log(/^0(?! \d+$)/.test('00123')); // true
console.log(/^0(?! \d+$)/.test('088770123')); // true

How about this?


A simpler answer without using the or operator makes the leading digit optional:

^[1-9]?[0-9]$

Matches 0-99 disallowing leading zeros (01-09).


This should do the trick:

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


Answer:

^([1-9])?(\d)$

Explanation:

^          // beginning of the string
([1-9])?   // first group (optional) in range 1-9 (not zero here)
(\d)       // second group matches any digit including 0
$          // end of the string

Same as (Not grouping):

^[1-9]?\d$

Test:

https://regex101.com/r/Tpe9Ia/1


Try this it will help you

^([0-9]|[1-9][0-9])$


([1-9][0-9]+).*

this will be simple and efficient it will help with any range of whole numbers

([1-9][0-9\.]+).*

this expression will help with decimal numbers


You can use the following regex:

[1-9][0-9]\d|0


^(0{1,})?([1-9][0-9]{0,1})$

It includes: 1-99, 01-099, 00...1-

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号