tags:

views:

67

answers:

4

I want a regular expression for a number which is a continuous string of digits with no spaces - Please help ! Thankyou

A: 

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

MCA
You meant `\d`, right? Use `+` instead of `*` : `\d*` will match even and empty string.
Amarghosh
`*` means `0 or more`, so this would match `[0-9]*` would match an empty string. Worse, given the string `abcd` this would return 5 matches: one at the start and end of the string, and one between each character. Each match would be 0-length. `+` stipulates `1 or more` and wouldn't do this.
James Polley
+5  A: 

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.

Gumbo
`^` and `$` mark the beginning and end of line respectively - this won't match `a123456b` because of the non-digit characters. It's not clear to me that that's what the OP was after.
James Polley
Then again, it's not clear that it's *not* what the OP wants either.
James Polley
+1  A: 

\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')
[]
James Polley
+2  A: 

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.

Danail