Get whole line with java.util.scanner.hasNext (regex)

I'm doing something in Java that requires the input to match the pattern ^ [1-5] $. I have to have a while loop going through each line of input, checking it against the pattern, and outputting an error message if it isn't.

Sudo code:

while (regex_match(/^[^1-5]$/,inputLine)) {  
    print ("Please enter a number between 1 and 5! ");  
    getNextInputLine();
}  

      

I can use java.util.Scanner.hasMatch("^[^1-5]$")

, but this will only match one token, not the whole string. Any idea on how to make hasMatch match the entire string? (Setting the separator to "\ n" or "\ 0" does not work.)

Edit: If this is not possible, is there any other way to do it?

+2


a source to share


1 answer


It is not clear what exactly you are asking.


Another possibility is that perhaps you not only need the next token ^[1-5]$

, but you want the entire next line to match that. If so, then there might be something like this you need:



String line = scanner.nextLine();
if (!line.matches("^[1-5]$")) {
  // error message
} else {
  int num = Integer.parseInt(line);
}

      

If you want to check if nextLine()

this pattern matches without using this line, you can do the following:

if (scanner.findInLine("^[1-5]$") != null) {
  // nextLine().matches("[1-5]");
}

      

+5


a source







All Articles