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

Time:09-30

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

[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

CodePudding user response:

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;
  • Related