问题
Suppose, I need to match parentheses containing whitespace.
Here is a snippet:
String input = "( ) ( ) ( )";
Pattern pattern = Pattern.compile("\\(\\s\\)");
Scanner scanner = new Scanner(input);
scanner.useDelimiter("\\n");
Matcher matcher = pattern.matcher(input);
System.out.println(scanner.hasNext(pattern)); // false
System.out.println(matcher.find()); // true
System.out.println(matcher.start(0) + " " + matcher.end(0)); // 0 3
Matcher does exactly what I need, but Scanner doesn't.
The question was not asked correctly. My purpose was to grab sequentially all ( ) tokens in string with scanner, because matcher seems to have inconvenient API for such task. I should have read documentation thoroughly.
The method what I need is:
scanner.findInLine(pattern);
回答1:
Checking the javadoc from Scanner.hasNext(Pattern):
Returns true if the next complete token matches the specified pattern...
So, since your pattern doesn't match the whole token "( ) ( ) ( )" it will return false.
The Scanner however has a function called findInLine that can do what you want:
scanner.findInLine(pattern); // returns "( )" or null if not found
(however, this method can skip characters...)
回答2:
When you use "\\n" as delimiter (and hence override the default value which is a whitespace) the whole input "( ) ( ) ( )" becomes a token.
As the hasNext tries to match the complete token with the pattern it returns false.
From the documentation the method Scanner.hasNext(Pattern pattern)
Returns true if the next complete token matches the specified pattern.
So in your case the method call is actually trying to match "( ) ( ) ( )" with a "( )".
回答3:
String input = "( ) ( ) ( )";
Pattern pattern = Pattern.compile("\\(\\s\\)");
Scanner scanner = new Scanner(input);
scanner.useDelimiter(pattern); //**CHANGED**
Matcher matcher = pattern.matcher(input);
System.out.println(scanner.hasNext()); //**CHANGED**
System.out.println(matcher.find());
System.out.println(matcher.start(0) + " " + matcher.end(0)); // 0 3
Update your code as above.
You misunderstood useDelimiter(). You have to set Pattern as delimiter to your Scanner object.
来源:https://stackoverflow.com/questions/15251157/javas-scanner-how-to-match-whitespace