Using C# Regex.IsMatch to validate 4 digit string?

  • Thread starter Thread starter Byron
  • Start date Start date
B

Byron

All I am trying to do is use Regex.IsMatch to validate that a string is
either empty, or exactly 4 characters (digits) in length. In other words,
the strings, "", and "1234" should pass, whereas "123", "abcd", and "12345"
should fail. I know there has to be a simple answer to this, but right now
I can't find it. I tried using:

if (str.Length == 0)

return true;

if (Regex.IsMatch(str, "[0-9]^4"))

return true;

but this does not work. Variations such as

Regex.IsMatch("1234", @"\d\d\d\d") come close, but also result in "12345"
validating.

Any help would be greatly appreciated.
 
Hi Byron,

You have to use ^ and $ to indicate start and end of the string:
Regex.IsMatch("1234", @"^\d\d\d\d$")

should do the trick.

Cheers,
 
That did the trick. Thanks for the quick reply


Ignacio Machin ( .NET/ C# MVP ) said:
Hi Byron,

You have to use ^ and $ to indicate start and end of the string:
Regex.IsMatch("1234", @"^\d\d\d\d$")

should do the trick.

Cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

Byron said:
All I am trying to do is use Regex.IsMatch to validate that a string is
either empty, or exactly 4 characters (digits) in length. In other words,
the strings, "", and "1234" should pass, whereas "123", "abcd", and "12345"
should fail. I know there has to be a simple answer to this, but right now
I can't find it. I tried using:

if (str.Length == 0)

return true;

if (Regex.IsMatch(str, "[0-9]^4"))

return true;

but this does not work. Variations such as

Regex.IsMatch("1234", @"\d\d\d\d") come close, but also result in "12345"
validating.

Any help would be greatly appreciated.
 
Back
Top