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?
a source to share
It is not clear what exactly you are asking.
-
hasNextInt()
can tell you if there isint nextInt()
. Then you can check if it is between 1-5 and if it doesn't ask for another. This would seem to be the cleanest option without even using a regex. -
hasNext("[1-5]")
can tell you if the whole part of the next token isnextInt()
between 1-5. It's actually a bit strict if the next token, say"005"
, doesn't match. You can make the regex more complex to accommodate this, but at this point the first option above becomes even more attractive. -
findInLine(String pattern)
can match pattern by ignoring delimiters, skipping any input that doesn't match. For example, you can extract a number from an input like"I want to buy 3 apples, please!"
. This is probably not what you want (but it is not clear from the question).
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]");
}
a source to share