Regular Expression - 2 letters and 2 numbers in C#

后端 未结 3 1265
佛祖请我去吃肉
佛祖请我去吃肉 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
    }
    

提交回复
热议问题