Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Regex Matcher encountering NullPointerException, when handed null input [duplicate]

I am trying to use the java regex matcher-class and I'm encountering a NullPointerException in my code:

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!");
}

Stack Trace: (line: 173 is in the above code where the comment "//EXCEPTION IS HERE" is located)

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)

The value of the input should be what the user enters in the console. The regex should match the input to validate that it meets the regex requirements.

like image 515
Brenton Avatar asked Dec 22 '16 15:12

Brenton


2 Answers

It's not explicitly stated in the javadoc of Pattern#matcher, but it will not work with a null input (it creates a new Matcher instance which will reset itself upon initialization, leading to the observed exception). You'll have to explicitly test for != null beforehand.

Side note: Although undocumented, this has already been declined to change:

The current API doc does not explicitly or implicitly mention whether or not a NPE will/should be thrown. But it is difficult to define a good semantics for a "null" in Matcher as a legal input text, should it be semantically equivalent to empty string ""? Obviously not. Then, what the match/find result should be expected when match null against boundary pattern like "^" and "$" (probably no match/no find for all patterns), and who will be benefited from such a semantics? The described use scenario is reasonable but should be easily achieved by use an empty string "" instead. Dont see a strong justification to "fix" the current behavior. Instead, updating the package spec to describe the NPE behavior might be a better choice.

like image 185
Marvin Avatar answered Oct 22 '22 14:10

Marvin


I added input = in.nextLine(); above the matcher line.

String input = null;
System.out.println("\nEnter your username: ");
input = in.nextLine();
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!");
}
like image 33
Brenton Avatar answered Oct 22 '22 16:10

Brenton