^([0-9])+$ RegEx supports numbers and spaces, but how to support empty lines too?

21,003

Solution 1

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.

Solution 2

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

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

Solution 3

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]*$
Share:
21,003
JoHa
Author by

JoHa

Updated on July 06, 2022

Comments

  • JoHa
    JoHa almost 2 years

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

  • Lordn__n
    Lordn__n over 13 years
    @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.
  • wds
    wds over 13 years
    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.
  • skube
    skube almost 7 years
    Doesn't \d* match zero and thus infinitely?