BradG
BradG

Reputation: 740

Regex to require at least one digit or to be left blank

Need some advice for a regex expression I am trying to create.

I need to check whether the string contains at least one digit (0-9) OR it can be left empty.

This is my regex that checks for a digit:

(.*[0-9]){1}.*$

How can I modify this to allow for empty string?

Upvotes: 3

Views: 487

Answers (5)

DKing
DKing

Reputation: 595

Perhaps you could try something like this:

^($|.*[0-9])

Even though ^ and $ do not consume any characters, they can still be used inside, as well as outside, of groups.

Also, depending on what you're doing, you may not even need the groups:

^$|.*[0-9]

Upvotes: 3

ctwheels
ctwheels

Reputation: 22817

OP mentioned jquery in comments below the question.

You can simply test to see if a digit exists in the string using \d and test() and also test the string's length as shown in the snippet below. This greatly simplifies the regex pattern and the test.

var a = [
  'cdjk2d', '', //valid
  'abc', ' ' //invalid
]
a.forEach(function(s){
  if(s.length === 0 || /\d/.test(s)) {
    console.log(s)
  }
})

Upvotes: 0

revo
revo

Reputation: 48711

Apply both conditions with a ? (optional) mark:

^(\D*\d.*)?$

Upvotes: 0

Jan
Jan

Reputation: 43169

You could use

^(?:(?=\D*\d)|^$).*


This says:

^             # start of the string
(?:
    (?=\D*\d) # either match at least one number
    |         # or
    ^$)       # the empty string
.*            # 0+ characters

See a demo on regex101.com.

Upvotes: 2

bobble bubble
bobble bubble

Reputation: 18490

You can use an optional non-capturing group like this

^(?:.*?\d.*)?$

See demo at regex101

Upvotes: 3

Related Questions