Reputation: 740
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
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
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
Reputation: 43169
You could use
^(?:(?=\D*\d)|^$).*
^ # start of the string
(?:
(?=\D*\d) # either match at least one number
| # or
^$) # the empty string
.* # 0+ characters
Upvotes: 2
Reputation: 18490
You can use an optional non-capturing group like this
^(?:.*?\d.*)?$
Upvotes: 3