Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression - 2 letters and 2 numbers in C#

Tags:

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}")){ } 
like image 963
Dan-SP Avatar asked Mar 09 '12 18:03

Dan-SP


2 Answers

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.

like image 52
Ry- Avatar answered Sep 30 '22 14:09

Ry-


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} 
like image 21
Jason Carter Avatar answered Sep 30 '22 14:09

Jason Carter