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

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.
 
I

Ignacio Machin \( .NET/ C# MVP \)

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,
 
B

Byron

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top