Regular Expression - 2 letters and 2 numbers in C#

后端 未结 3 1229
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-03 22:30

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

相关标签:
3条回答
  • 2021-01-03 22:55

    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
    }
    
    0 讨论(0)
  • 2021-01-03 22:57

    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}
    
    0 讨论(0)
  • 2021-01-03 23:11

    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.

    0 讨论(0)
提交回复
热议问题