tags:

views:

55

answers:

5

The RegEx ^([0-9])+$ supports numbers and spaces. However, I want it to support empty lines too. How?

A: 

^([0-9])*$ Change + to *

Btw your code does not support spaces for adding spaces regex should have [0-9\s]

Hasan Khan
+2  A: 

Use this instead:

^([0-9])*$

or, more simply:

^\d*$

\d means any digit (0-9). + means one or more matches. * means zero or more matches.

cletus
\d is Perl specific and won't work if OP is using e.g. grep
Jonathan Maddison
@Jonathon `\d` is most certainly *not* Perl specific. I can't claim universal functionality but Perl only? Not a chance. Java, C+, PHP and Python all allow it, just off the top of my head.
cletus
as cletus points out, most programming languages use some form of perl-like notation for digits, spaces, etc. The equivalent in POSIX regexes would be [[:digit:]] I suppose.
wds
+1  A: 

Also, note that in your original (and the recommendations here), you are making a tagged group of just the first digit. If you want the entire number in the capture, you need the + (or *) inside the perens:

^([0-9]*)$

On the other hand, if you don't need a capture, you don't need the perens at all:

^[0-9]*$
James Curran
A: 

By empty line don't you mean a line with a carriage return? Wouldn't that simply be ^(\d*\s*\n)$?

stocherilac
A: 

Read the... read the manual.

hlynur