Dmitry D
Dmitry D

Reputation: 760

Java's Scanner. How to match whitespace?

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);

Upvotes: 2

Views: 1112

Answers (3)

user2030471
user2030471

Reputation:

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 "( )".

Upvotes: 1

dacwe
dacwe

Reputation: 43504

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...)

Upvotes: 1

Aman J
Aman J

Reputation: 1855

        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.

Upvotes: 0

Related Questions