0Pricing
Java Academy · Lesson

Finding and Matching

matches, find, lookingAt.

Three Ways to Apply a Pattern

Matcher offers three core tests:

  • matches() requires the whole input to match.
  • lookingAt() requires a match at the start.
  • find() searches for a match anywhere.
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Main {
    public static void main(String[] args) {
        Matcher m = Pattern.compile("\\d+").matcher("42");
        System.out.println(m.matches());
    }
}

matches: Whole Input

matches returns true only if the entire string conforms to the pattern, as if it were anchored at both ends.

import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        Pattern p = Pattern.compile("\\d+");
        System.out.println(p.matcher("123").matches());
        System.out.println(p.matcher("123abc").matches());
    }
}

All lessons in this course

  1. Compiling Patterns
  2. Finding and Matching
  3. Capturing Groups
  4. Replacing with Regex
← Back to Java Academy