ray
ray

Reputation: 8699

Regex: Return value can match or be empty

How can I change the following regular expression to make empty values (a.k.a String.Empty) also match:

^[0-9]{4}$

I've tried the following but have had no success:

^[0-9]{4}$|^$
(^[0-9]{4}$)*

I'm using a VB.Net Application and comparing with the namespace System.Text.RegularExpressions.

Note: The regular expression is a four-digit number representing the last four of an SSN; and it is optional. Therefore, I would like to resolve the match with one regular expression than have to do something like this:

If myString.Length = 0 Then
   'This is Ok
Else
   'Do the regular expression comparison here
End if

Upvotes: 1

Views: 1042

Answers (3)

Mrchief
Mrchief

Reputation: 76218

Try this pattern:

^[0-9]{0,4}$

It'll match the input having 0-4 digits.

If you only want 0 or 4 digits, use this:

^[0-9]{4}$|^$

Demo: http://regexhero.net/tester/?id=cd85169b-f5f8-457e-8f8e-759816213fb5

Upvotes: 2

Prisoner
Prisoner

Reputation: 27628

This would do it: ^([0-9 ]{4})?$

Upvotes: 1

Anton Vidishchev
Anton Vidishchev

Reputation: 1389

Please try the following regex:

^([0-9]{4})?$

Hope this helps.

Upvotes: 0

Related Questions