简体   繁体   English

如何验证文本框中的字符串仅包含2个字符和3个数字?

[英]How to validate that a string from a textbox contains only 2 characters and 3 numbers?

I have checked other answers and am not finding what I need to know. 我检查了其他答案,但找不到我需要知道的内容。 I have a variable named nationalID which can only contain 2 characters and 3 numbers (ex. aa123) How do I say this in java? 我有一个名为nationalID的变量,该变量只能包含2个字符和3个数字(例如aa123)如何在Java中说呢? I am using Netbeans and have looked at all of the methods that pops up but I am not seeing anything that will help me. 我正在使用Netbeans,并查看了所有弹出的方法,但没有发现任何对我有帮助的方法。 This is what I have so far. 到目前为止,这就是我所拥有的。

private String validator(String nationalID, String lastName, String firstName, String dateOfBirth) {
    // nationalID should have 2 characters and 3 digits ex. AB123
    // dateOfBirth should be yyyy-mm-dd

    if(nationalID.length() != 5 || nationalID.){
        String err;
        return err =  "Your National ID has to be 5 characters long";
    }

    return "";
}

Try using matches method of String with regex like: 尝试使用匹配的字符串的方法与像正则表达式:

 if(nationalID.matches("[A-Za-z]{2}[0-9]{3}")) {
     System.out.println("Yes it does contains pattern");
 }

[A-Za-z]{2} Means be it any two known character either between AZ or az. [A-Za-z] {2}是指AZ或az之间的任何两个已知字符。
[0-9]{3} Means be it any combination of numbers between 0-9 repeated thrice which follows two known characters. [0-9] {3}表示在0-9重复三次之间跟随两个已知字符的数字的任意组合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM