改进我的验证

Sma*_*end -1 java validation performance

当用户输入他们的ID我希望它具有特定格式时,他们大多在评论中解释.我想知道他们是否更容易更有效地这样做.另外,是否有办法将输入的字母更改为我完成代码的方式或任何其他方法.

private boolean setCustomerID(String id) {
    //Validates the customerID contains 3 letters a hypthen then 4 numbers
    if ((id.charAt(0) < 'A' || id.charAt(0) > 'Z')
            || (id.charAt(1) < 'A' || id.charAt(1) > 'Z')
            || (id.charAt(2) < 'A' || id.charAt(2) > 'Z')
            || (id.charAt(3) != '-')
            || !isDigit(id.charAt(4))
            || !isDigit(id.charAt(5))
            || !isDigit(id.charAt(6))
            || !isDigit(id.charAt(7))) {
        return false;
        //Checks the user enters P, B or C for first letter
    } else if ((id.charAt(0) == 'P' || id.charAt(0) == 'B' || id.charAt(0) == 'E')
            //Checks the second and third letter are in the correct region
            && ((id.charAt(1) == 'S' && id.charAt(2) == 'C') 
            || (id.charAt(1) == 'S' && id.charAt(2) == 'C')
            || (id.charAt(1) == 'W' && id.charAt(2) == 'A')
            || (id.charAt(1) == 'N' && id.charAt(2) == 'I')    
            || (id.charAt(1) == 'N' && id.charAt(2) == 'E')    
            || (id.charAt(1) == 'N' && id.charAt(2) == 'W')    
            || (id.charAt(1) == 'M' && id.charAt(2) == 'I')    
            || (id.charAt(1) == 'E' && id.charAt(2) == 'A')    
            || (id.charAt(1) == 'S' && id.charAt(2) == 'E')
            || (id.charAt(1) == 'S' && id.charAt(2) == 'W'))){ 
        //    SC (Scotland), WA (Wales), NI (Northern Ireland), NE (North-East), NW (North-West),
        //MI (Midlands), EA (East Anglia), SE (South-East), SW (South-West).
        return true;
    }
        return false;
    }
Run Code Online (Sandbox Code Playgroud)

rco*_*eia 7

使用正则表达式.

private boolean matchCustomerID(String id) {
    return id.matches("^[PBE](?:SC|WA|NI|NE|NW|MI|EA|SE|SW)-\\d{4}\\b");
}
Run Code Online (Sandbox Code Playgroud)

  • 我建议`^ [PBE](NI | NE | NW | MI | EA | SE | SW) - [0-9] {4}\b`,以确保像`dPSE-1234`和`PSE-这样的字符串12345`没有被错误地包括在内? (3认同)
  • 另外,`\\ d`是一个预定义的常量,可以替换`[0-9]`. (2认同)