Java Regex Matcher在传递null输入时遇到NullPointerException

Bre*_*ton 5 java nullpointerexception

我试图使用java正则表达式匹配器类,我在我的代码中遇到NullPointerException:

String input = null;
System.out.println("\nEnter your username: ");
Matcher matcher = VALID_USERNAME_REGEX.matcher(input); //EXCEPTION IS HERE
if (matcher.find()) {
    username = input;
} else {
    input = null;
    System.out.println("\nInvalid input, please try again!");
}
Run Code Online (Sandbox Code Playgroud)

堆栈跟踪:(行:173在上面的代码中,注释" //EXCEPTION IS HERE"所在的位置)

Exception in thread "main" java.lang.NullPointerException
    at java.util.regex.Matcher.getTextLength(Unknown Source)
    at java.util.regex.Matcher.reset(Unknown Source)
    at java.util.regex.Matcher.<init>(Unknown Source)
    at java.util.regex.Pattern.matcher(Unknown Source)
    at org.console.Interface.createAccount(Interface.java:173)
    at org.console.Interface.login(Interface.java:78)
    at org.application.Application.run(Application.java:31)
    at org.application.Application.main(Application.java:37)
Run Code Online (Sandbox Code Playgroud)

输入的值应该是用户在控制台中输入的值.正则表达式应匹配输入以验证它是否满足正则表达式要求.

Mar*_*vin 6

它没有在javadoc中明确声明Pattern#matcher,但它不能用于null输入(它创建一个新的Matcher实例,它将在初始化时重置自身,导致观察到的异常).你必须!= null事先明确地测试.

附注:虽然没有记录,但已经拒绝改变:

当前的API文档没有明确或隐含地提及是否应该抛出NPE.但是,如果它在语义上等同于空字符串"",那么很难在Matcher中为"null"定义一个良好的语义作为合法的输入文本?显然不是.那么,当匹配null时,对于像"^"和"$"这样的边界模式(可能没有匹配/没有找到所有模式),以及谁将从这样的语义中受益,应该期望匹配/查找结果是什么?所描述的使用场景是合理的,但应该通过使用空字符串""来轻松实现.没有看到"修复"当前行为的强有力理由.相反,更新包规范以描述NPE行为可能是更好的选择.