8

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.

Paul Brinkley
  • 6,283
  • 3
  • 24
  • 33
Brenton
  • 264
  • 1
  • 2
  • 10

2 Answers2

12

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.

Marvin
  • 13,325
  • 3
  • 51
  • 57
2

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!");
}
TylerH
  • 20,799
  • 66
  • 75
  • 101
Brenton
  • 264
  • 1
  • 2
  • 10