DanCaparroz
DanCaparroz

Reputation: 820

Regular Expression - 2 letters and 2 numbers in C#

I am trying to develop a regular expression to validate a string that comes to me like: "TE33" or "FR56" or any sequence respecting 2 letters and 2 numbers.

The first 2 characters must be alphabetic and 2 last caracters must be numbers.

I tried many combinations and I didn't have success. Last one I tried:

if(Regex.IsMatch(myString, "^[A-Za-z]{2}[0-9]{2}")){
}

Upvotes: 28

Views: 152512

Answers (3)

Ry-
Ry-

Reputation: 224906

You're missing an ending anchor.

if(Regex.IsMatch(myString, "^[A-Za-z]{2}[0-9]{2}\z")) {
    // ...
}

Here's a demo.


EDIT: If you can have anything between an initial 2 letters and a final 2 numbers:

if(Regex.IsMatch(myString, @"^[A-Za-z]{2}.*\d{2}\z")) {
    // ...
}

Here's a demo.

Upvotes: 46

Jason Carter
Jason Carter

Reputation: 925

This should get you for starting with two letters and ending with two numbers.

[A-Za-z]{2}(.*)[0-9]{2}

If you know it will always be just two and two you can

[A-Za-z]{2}[0-9]{2}

Upvotes: 8

James Hill
James Hill

Reputation: 61792

Just for fun, here's a non-regex (more readable/maintainable for simpletons like me) solution:

string myString = "AB12";

if( Char.IsLetter(myString, 0) && 
    Char.IsLetter(myString, 1) && 
    Char.IsNumber(myString, 2) &&
    Char.IsNumber(myString, 3)) {
    // First two are letters, second two are numbers
}
else {
    // Validation failed
}

EDIT

It seems that I've misunderstood the requirements. The code below will ensure that the first two characters and last two characters of a string validate (so long as the length of the string is > 3)

string myString = "AB12";

if(myString.Length > 3) {    
    if( Char.IsLetter(myString, 0) && 
        Char.IsLetter(myString, 1) && 
        Char.IsNumber(myString, (myString.Length - 2)) &&
        Char.IsNumber(myString, (myString.Length - 1))) {
        // First two are letters, second two are numbers
      }
      else {
        // Validation failed
    }
}
else {
   // Validation failed
}

Upvotes: 5

Related Questions