views:

237

answers:

1

I'm doing something in Java that requires input to be matched against the pattern ^[1-5]$. I should have a while loop looping through each line of input, checking it against the pattern, and outputting an error message if it does not.

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 that will only match a single token, not the entire line. Any idea on how to make hasMatch match against the entire line? (Setting the delimiter to "\n" or "\0" doesn't work.)

Edit: If this isn't possible, is there some other way to do it?

+2  A: 

It's not clear what you're asking exactly.

  • hasNextInt() can tell you if there's an int nextInt(). You can then check if it's between 1-5, and if it isn't prompt for another. This would seem to be the cleanest option, without even using regex.

  • hasNext("[1-5]") can tell you if the entirety of the next token is a nextInt() between 1-5. This is actually a bit strict in that if the next token is, say, "005", it doesn't match. You can make the regex more complicated to accommodate this, but at that point the first option above becomes even more attractive.

  • findInLine(String pattern) can find a pattern, ignoring delimiters, skipping any input that doesn't match. You can extract the number from an input like "I want to buy 3 apples, please!", for example. This likely isn't what you need (but it isn't clear from the question).


Another possibility is that perhaps not only do you need the next token to be ^[1-5]$, but you want the entire next line to match that. If that's the case, then maybe something like this is what 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 the nextLine() matches that pattern without consuming that line, then you can do the following:

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