The matches() method

The matches() method attempts to match the entire region against the pattern and returns true only if the entire region matches against the pattern.

Let's look at the following code to understand the use of this method better:

package example.regex; 

import java.util.regex.*;

class MatcherMatchesExample
{
public static void main (String[] args)
{

final Pattern pattern1 = Pattern.compile("mastering");
final Pattern pattern2 = Pattern.compile("mastering.*");
final Pattern pattern3 = Pattern.compile("regular.*");

String input = "mastering regular expressions";

Matcher matcher = pattern1.matcher(input);
System.out.printf("[%s] => [%s]: %s%n", input, matcher.pattern(),
matcher.matches());

// update the matcher ppattern with a new pattern
matcher.usePattern(pattern2);
System.out.printf("[%s] => [%s]: %s%n", input, matcher.pattern(),
matcher.matches());

// update the matcher ppattern with a new pattern
matcher.usePattern(pattern3);
System.out.printf("[%s] => [%s]: %s%n", input, matcher.pattern(),
matcher.matches());

}
}

This will give following output after running:

[mastering regula expressions] => [mastering]: false 
[mastering regula expressions] => [mastering.*]: true
[mastering regula expressions] => [regular.*]: false

As you can see, we get true only when our pattern matches the entire region from the start to end, which is using this regex: mastering.*

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

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