Rinktacular
Rinktacular

Reputation: 1136

Using Regex to recognize pattern in string

I apologize if this is a repeat question, as I know there are many about Regex on StackOverflow, but I have yet to find an answer or a level of help I need.

I have a string that needs to be a length of 8 where:

  • The first two characters are letters

  • The next five characters are numbers

  • The last character is a letter

For example: "AB12345C"

I have been using the examples from MSDN & DotNetPerls to try and understand how to use arguments properly, but after a couple days of reading around I still can't get it to pass.

I am currently trying to use:

public Tuple<bool, string> stringFormatCheck(string input)
{            
     if (Regex.IsMatch(input, @"^[a-zA-Z]\d{2}[0-9]\d{5}[a-zA-Z]$") == true)
        return Tuple.Create(true, "String is Fine");
     else
        return Tuple.Create(false, "String Format is incorrect");
}

Can someone show me how to use this argument properly or somewhere I can get a better understanding of the Regex Class? Thank you.

EDIT1: The second Z in my first argument is now capitalized.

Upvotes: 1

Views: 302

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186678

The right pattern is

"^[A-Za-z]{2}[0-9]{5}[A-Za-z]$"

with, IMHO, clear interpretation:

^           - string start (anchor)
[A-Za-z]{2} - 2 letters A..Z or a..z
[0-9]{5}    - 5 digits 0..9
[A-Za-z]    - letter A..Z or a..z
$           - string end (anchor)

And so the implementation can be

public Tuple<bool, string> stringFormatCheck(string input)
{            
    if (Regex.IsMatch(input, @"^[A-Za-z]{2}[0-9]{5}[A-Za-z]$"))
        return Tuple.Create(true, "String is Fine");
    else
        return Tuple.Create(false, "String Format is incorrect");
}

Please, notice, that [0-9] is a better choice than \d since you, probably, don't want let, say, Persian digits like "AB۰۱۲۳۴C" ;

Upvotes: 1

adv12
adv12

Reputation: 8551

Try this: ^[a-zA-Z]{2}[0-9]{5}[a-zA-Z]$

Your regex: ^[a-zA-z]\d{2}[0-9]\d{5}[a-zA-Z]$ doesn't work for multiple reasons. First, the second z should be capitalized. Then, the first \d is trying to match a digit, so you're saying "Match any letter then two digits." You make the same mistake with the second \d: you say "Match any digit ([0-9]) and then match 5 digits (\d{5}).

Upvotes: 1

Related Questions