The find() and find(int start) methods

These find methods attempt to find the next subsequence of the input sequence that matches the pattern. These methods return true only if a subsequence of the input matches this matcher's pattern. If multiple matches can be found in the text, then the find() method will find the first, and then for each subsequent call to find(), it will move to the next match.

An example code will make it clearer:

package example.regex; 

import java.util.regex.*;

class MatcherFindExample
{
public static void main (String[] args)
{
final String input = "some text <value1> anything <value2><value3>
here";

/* Part 1 */
final Pattern pattern = Pattern.compile("<([^<>]*)>");

Matcher matcher = pattern.matcher(input);

while (matcher.find()) {
System.out.printf("[%d] => [%s]%n",
matcher.groupCount(), matcher.group(1));
}

/* Part 2 */
// now use similar pattern but use a named group and reset the
// matcher
matcher.usePattern(Pattern.compile("<(?<name>[^<>]*)>"));
matcher.reset();

while (matcher.find()) {
System.out.printf("[%d] => [%s]%n",

matcher.groupCount(), matcher.group("name"));
}
}
}

This will output the following:

[1] => [value1] 
[1] => [value2]
[1] => [value3]
[1] => [value1]
[1] => [value2]
[1] => [value3]

As you can see in the preceding code, we are extracting all the text that is inside the angular brackets using a negated character class, [^<>]*, inside a capturing group.

In Part 1 of the code, we use regular captured group and matcher.group(1) to extract and print the subsequence captured in group number 1. The numbering of the groups starts each time we execute find() and the previous captures are wiped off. Even though it is in a loop, it is always group(1) in the example because for each iteration, there can be more than one group.

In Part 2, we use a named capturing group and an overloaded method call to matcher.group("name") to extract the subsequence captured by the given group name.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.7.174