Regular Expressions problem

K

Kristof Van Praet

Hello group,

I have the following problem with a regular expression:

I try to check whether or not a string exists of exactly two numbers (e.g.
12). Therefore, I have the following regular expression "[0-9]{2}".
I try to use this in .NET (1.1 SP1) with the System.Text.RegularExpressions
class like this:

Console.WriteLine(regex.IsMatch("1").ToString());
Console.WriteLine(regex.IsMatch("10").ToString());
Console.WriteLine(regex.IsMatch("100").ToString());

This gives me the following results:
False
True
True

This is not what I expected. I expected:
False
True
False

When I tried "[0-9]{2,2}" I also got
False
True
True


Can anyone tell me what is wrong with my regular expression?

Thx,
Kristof
 
N

Niki Estner

"IsMatch" is a bit similar to "IndexOf": It returns true is the specified
pattern matches anywhere in the string. If you match "[0-9]{2}" against
"100", it will match on "10", ignoring the rest.
If you want to check the whole string, you have to use a pattern like:
"^[0-9]{2}$". "^" only matches on the beginning of the string, "$" on the
end of the string.

Niki
 
K

Kristof Van Praet

Niki, thanks for the help. It works OK now :).

Kristof

Niki Estner said:
"IsMatch" is a bit similar to "IndexOf": It returns true is the specified
pattern matches anywhere in the string. If you match "[0-9]{2}" against
"100", it will match on "10", ignoring the rest.
If you want to check the whole string, you have to use a pattern like:
"^[0-9]{2}$". "^" only matches on the beginning of the string, "$" on the
end of the string.

Niki

Kristof Van Praet said:
Hello group,

I have the following problem with a regular expression:

I try to check whether or not a string exists of exactly two numbers
(e.g. 12). Therefore, I have the following regular expression "[0-9]{2}".
I try to use this in .NET (1.1 SP1) with the
System.Text.RegularExpressions class like this:

Console.WriteLine(regex.IsMatch("1").ToString());
Console.WriteLine(regex.IsMatch("10").ToString());
Console.WriteLine(regex.IsMatch("100").ToString());

This gives me the following results:
False
True
True

This is not what I expected. I expected:
False
True
False

When I tried "[0-9]{2,2}" I also got
False
True
True


Can anyone tell me what is wrong with my regular expression?

Thx,
Kristof
 

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