有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java验证字符串输入

如何在Java中验证此字符串输入

Two letter followed by three digits and a letter. The last letter can only be B for Business Account or N for Non-Business Account

例如“JB213B”或“JB231N”

编辑:好的,我现在使用正则表达式,谢谢

虽然现在我提出了如何实际执行验证,但以下是我到目前为止所做的

            System.out.println("Enter your reference");
            String reference = keyboard.next();
            String regex = "[A-Z]{2}[0-9]{3}[B|N]";
            boolean match = reference.matches(regex);
            while (!match)
            {
                System.out.println("That isn't a valid reference");
                reference = keyboard.next();
                match = reference.matches(regex);
            }

共 (4) 个答案

  1. # 1 楼答案

    使用如下所示的正则表达式

    String st = "JB213B";
    String regex= "[A-Z]{2}\\d{3}[BN]";
    
    boolean match = st.matches(regex);
    
  2. # 2 楼答案

    您可以使用正则表达式来实现这一点

    在这种情况下,表达式将是^[A-Z]{2}[0-9]{3}[B|N]$

    ThisString类的.matches()方法的引用

    同样,您也可以使用Pattern类来查找匹配项This是这方面的参考

    用法:

        String strToTest = "AB123B";
        String pattern = "^[A-Z]{2}[0-9]{3}[B|N]$";
        Pattern p = Pattern.compile(patern);
        Matcher m = p.matcher(strToTest);
        boolean b = m.matches();
    

    性能比较:

    “使用正则表达式”或“使用字符串比较”哪个更好

    这个问题总是有争议的。但我发现,理解需求的复杂性在任何情况下都没有什么帮助

    如果需要进行许多字符串比较,使用正则表达式可以跳过这些比较,那么我将使用正则表达式

    但也应该考虑使用多个和/或复杂的正则表达式会对性能产生影响,因为正则表达式的评价也是一个繁琐且复杂的编译器程序(与字符串操作相比)。p>

    另一方面,字符串比较的使用也容易出错,因为我们直接处理索引和剥离不必要的部分

  3. # 3 楼答案

    为了确保有人为非正则表达式的可能性而战:

    public boolean isValid(String s) {
        return s.length() == 6 &&
            s.charAt(0) >= 'A' && s.charAt(0) <= 'Z' &&
            s.charAt(1) >= 'A' && s.charAt(1) <= 'Z' &&
            s.charAt(2) >= '0' && s.charAt(2) <= '9' &&
            s.charAt(3) >= '0' && s.charAt(3) <= '9' &&
            s.charAt(4) >= '0' && s.charAt(4) <= '9' &&
            (s.charAt(5) == 'B' || s.charAt(5) == 'N');
    }
    
  4. # 4 楼答案

    可以使用matches()方法将字符串与正则表达式进行比较

    // Match A-Z twice, 0-9 three times, and B or N once
    String myString = "JB213B";
    String myPattern = "[A-Z]{2}[0-9]{3}[BN]{1}";
    if(myString.matches(myPattern){
        // Do continuing logic
    } else {
        // Do error logic
    }