有 Java 编程相关的问题?

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

java String matches()方法工作不正常

所以我有这个方法:

   void verifySecretKey(String userEnters, Scanner input){

    while(true) {
        System.out.print("Enter the secret key:  ");
        userEnters = input.nextLine();
        System.out.println("\nVerifying Secret Key...");

        if (secretKey.matches(userEnters)) {
        System.out.println("Secret key verified!");
        break; } 

        else {
        System.out.println("The secret key does not follow the proper format!"); }
    }
}

由于某些原因,它不能正常工作。系统会自动为用户生成一个字符串secretKey,用户必须输入要验证的确切字符串。然而,即使输入了正确的字符串,它仍然表示它不正确

enter image description here

有时它是有效的,但大多数情况下它不是。我想知道我在这里做错了什么


共 (2) 个答案

  1. # 1 楼答案

    Matches将正则表达式作为参数。在屏幕截图中,您输入了oH-?bt-4#,其中包含一个?。这个字符在正则表达式中有特殊的含义。如果要使用String#match方法,必须转义所有特殊字符,例如使用Pattern.quote

    if (secretKey.matches(Pattern.quote(userEnters))) //...
    

    因为您的目标似乎是检查这两个字符串是否相同,所以可以使用String#equals方法:

    if (secretKey.equals(userEnters)) //...
    

    当你没有理由选择regex方法matches时,你应该坚持使用equals,因为它更有效

  2. # 2 楼答案

    据Javadoc报道

    public boolean matches(String regex)

    Tells whether or not this string matches the given regular expression.

    现在,"Java".matches("Java")是真的,因为正则表达式JavaJava匹配

    然而,有很多正则表达式本身并不匹配,如果随机生成字符串,很可能会找到一个正则表达式

    例如"a+bc".matches("a+bc")返回false,因为没有匹配文字字符+a+匹配一个或多个a

    随机字符串很可能会导致无法编译为正则表达式,在这种情况下,代码会抛出一个PatternSyntaxException,例如a[bc会因为一个不匹配的大括号而这样做

    要测试两个字符串是否完全相同,请使用.equals()