简体   繁体   中英

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?

You can use an optional non-capturing group like this

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

See demo at regex101

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]

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 .

Apply both conditions with a ? (optional) mark:

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

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) } }) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM