Reputation: 820
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
Reputation: 224906
You're missing an ending anchor.
if(Regex.IsMatch(myString, "^[A-Za-z]{2}[0-9]{2}\z")) {
// ...
}
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")) {
// ...
}
Upvotes: 46
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
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