3

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?

revo
  • 47,783
  • 14
  • 74
  • 117
BradG
  • 673
  • 1
  • 14
  • 26

5 Answers5

3

You can use an optional non-capturing group like this

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

See demo at regex101

bobble bubble
  • 16,888
  • 3
  • 27
  • 46
3

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]
DKing
  • 574
  • 5
  • 16
  • @S.Jovan Thanks. I suppose they aren't necessary. It depends on what's in the rest of the code, though. If a capture is wanted, perhaps `^(|.*[0-9].*)$` would have been the preferred form, instead. – DKing Mar 06 '18 at 19:57
  • I don't see why this should be the accepted answer, see **https://regex101.com/r/iG8mGs/3** where it only matches half the strings. Either use another `.*` right after the `[0-9]` or lookaheads altogether). – Jan Mar 06 '18 at 20:14
  • 1
    @Jan That green is only showing you what part matched. It depends on what one is trying to do. If you want to collect the whole match, then yes, you could add a `.*`. However, if you simply want to be sure that you got a match, you can stop as soon as you can confirm that. The question didn't specify that they wanted the whole group. As for lookaheads, that gets complicated and involves considering your implementation, and takes more processing, so I feel it's a bit much for this simple question. – DKing Mar 06 '18 at 20:25
  • Fair enough for checking only *if there is a match*. – Jan Mar 06 '18 at 20:41
2

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.

Jan
  • 42,290
  • 8
  • 54
  • 79
0

Apply both conditions with a ? (optional) mark:

^(\D*\d.*)?$
revo
  • 47,783
  • 14
  • 74
  • 117
0

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)
  }
})
ctwheels
  • 21,901
  • 9
  • 42
  • 77