Issue
Java 11 added some new methods to the Pattern
class (a compiled version of a regular expression), including:
- rel="noreferrer">
asPredicate
asMatchPredicate
I am trying to understand the difference between the two and when I would want to use one over the other?
Solution
Pattern.asPredicate
will return true if any part of the input string matches the Regular expression. You should use this method if you're testing some larger body of text for a certain pattern. For example, to test whether a comment from a user contains a hyperlink.Pattern.asMatchPredicate
will return true if the entire input string matches the Regular expression. You should use this method if you're testing the entire input for a certain pattern. For example, to validate the phone number of a user in their profile.
Pattern.asPredicate
internally uses Matcher.find()
, while Pattern.asMatchPrediate
internally uses Matcher.matches()
. So the difference between the two boils down to the difference between these two methods from the Matcher
class.
Below are some examples to showcase the difference. You can copy & paste below code in an online Java sandbox like https://www.compilejava.net/ to play around with it yourself.
import java.util.regex.Pattern;
import java.util.function.Predicate;
public class main
{
public static void main(String[] args) {
Pattern pattern = Pattern.compile("abc");
// asPredicate will match any part of the input string
Predicate<String> asPredicate = pattern.asPredicate();
// True, because abc is part of abc
System.out.printf("asPredicate: abc: %s\n", asPredicate.test("abc"));
// True, because abc is part of abcabc
System.out.printf("asPredicate: abcabc: %s\n", asPredicate.test("abcabc"));
// True, because abc is part of 123abc123
System.out.printf("asPredicate: 123abc123: %s\n", asPredicate.test("123abc123"));
// False, because abc is NOT part of 123
System.out.printf("asPredicate: 123: %s\n", asPredicate.test("123")); // -> false
// asMatchPredicate will only match the entire input string
Predicate<String> asMatchPredicate = pattern.asMatchPredicate();
// True, because abc exactly matches abc
System.out.printf("asMatchPredicate: abc: %s\n", asMatchPredicate.test("abc"));
// False, because abc does not exactly match abcabc
System.out.printf("asMatchPredicate: abcabc: %s\n", asMatchPredicate.test("abcabc"));
// False, because abc does not exactly match 123abc123
System.out.printf("asMatchPredicate: 123abc123: %s\n", asMatchPredicate.test("123abc123"));
// False, because abc does not exactly match 123
System.out.printf("asMatchPredicate: 123: %s\n", asMatchPredicate.test("123"));
}
}
Answered By - Martin Devillers
Answer Checked By - Mildred Charles (JavaFixing Admin)