Dadou
Dadou

Reputation: 25

Need to check the format of a string in c#

I have a string that needs to be the following format: XX999900. XX has to be only character no decimal followed by 6 digits.

So I thought of using regex in the following way:

string sPattern = @"^\\[A-z]{2}\\d{6}$";
indexNumber = "ab9999.00";
if (Regex.IsMatch(indexNumber, sPattern)
{
     // do whatever
}

It fails. Can somebody tell me what is wrong?

Upvotes: 0

Views: 130

Answers (4)

Oded
Oded

Reputation: 498904

I don't believe [A-z] is a valid character class. You certainly do not need \\ when using @.

Try this:

@"^[a-zA-Z]{2}\d{6}$"

If you need the format to have 4 numerals followed by a . then two more numerals, try this:

@"^[a-zA-Z]{2}\d{4}\.\d{2}$"

(Note that for .NET, \d will match numerals in any script, so you may want to replace it with [0-9] if you want to only match those)

Upvotes: 7

Brandon
Brandon

Reputation: 69953

A-z isn't valid (mixed case), and you don't have 6 consecutive digits. You have 4, a decimal, and then 2 more. Try

^[a-zA-Z]{2}\d{4}.\d{2}$

Upvotes: 1

Jim
Jim

Reputation: 2146

It fails because the value you are testing as a decimal in it and your regex pattern does not. Plus, your regex pattern is going to look at the entire string. That is ^ says start at the beginning of the string and $ says the end of the string. If you only want a "starts with", then drop the $ at the end of the pattern.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

You have way too many escape characters. Try:

string sPattern = @"^[a-zA-Z]{2}\d{6}$";

Upvotes: 1

Related Questions