开发者

reg expression for a number

开发者 https://www.devze.com 2022-12-15 09:27 出处:网络
I want a regular e开发者_JS百科xpression for a number which is a continuous string of digits with no spaces - Please help !

I want a regular e开发者_JS百科xpression for a number which is a continuous string of digits with no spaces - Please help ! Thankyou


This is the simplest:

^\d+$

This regular expression matches only sequences of one or more digits. ^ and $ mark the start and end of the string respectively.

But this would also allow numbers with leading zeros. If you don’t want that, use this:

^(0|[1-9]\d*)$

This matches either a single 0 or a number beginning with 1..9 followed by zero or more arbitrary digits.


If it is just for regex:

\d Matches any decimal digit; this is equivalent to the class [0-9].

So you can write

\d* or [0-9]* - from empty string to continuous string of digits

\d+ or [0-9]+ - at least one digit

If you want to know how to use this in specific language, specify the language pls.


\d+ will work in most implementations.

\d indicates digit - if your implemenation doesn't have this, use [0-9]+ instead.

+ means one or more of the preceeding pattern.

edit: Here's an example in python illustrating the difference between + and *:

>>> import re
>>> r = re.compile('[0-9]*')
>>> print r.findall('asdf')
['', '', '', '', '']
>>> r = re.compile('[0-9]+')
>>> print r.findall('asdf')
[]
>>> print r.findall('abc12345ghi')
['12345']
>>> r = re.compile('^[0-9]+$')
>>> print r.findall('abc12345ghi')
[]


d* or [0-9]* depending on implementation I guess...

0

精彩评论

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

关注公众号