Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex with 3-4 digits and two letters that can be anywhere in the string

I need a regex to validate barcodes that always have 3-4 digits and 2 letters that can be anywhere in the string. I have checked various solutions but nothing works as I would expect. The problem is that letters and numbers can be anywhere in the string.

Examples:

23BD9  = correct
AS5879 = correct
12AA87 = correct
A879A  = correct
2A45D9 = correct

ASE125 = incorrect
12F589 = incorrect
12456  = incorrect
ABCDE  = incorrect
12AA   = incorrect

I tried

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[A-Z + 0-9]{5,6}

[0-9]{2}[A-Z + 0-9]{3,4}

And many others, but unfortunately it works differently than it should

>Solution :

A regex isn’t well-suited for this task. I’d recommend LINQ, but you can also do this with a traditional for-loop if you need a more performant solution (it would be a micro-optimization, though).

var str = "23BD9";
int numbers = str.Count(x => char.IsNumber(x));

bool valid = (numbers == 3 || numbers == 4) &&
             (str.Count(x => char.IsLetter(x)) == 2);

You can drop the extra variable, but you’ll need to re-calculate the same expression two times:

var str = "23BD9";

bool valid = (str.Count(x => char.IsNumber(x)) == 3 || str.Count(x => char.IsNumber(x)) == 4) &&
              str.Count(x => char.IsLetter(x)) == 2;

Starting with C# 9.0, you can write this more elegantly without the need for an extra variable:

var str = "23BD9";

bool valid = (str.Count(x => char.IsNumber(x)) is 3 or 4) && 
              str.Count(x => char.IsLetter(x)) == 2;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading