0
0
JavaHow-ToBeginner · 3 min read

How to Use Pattern and Matcher in Java for Regex Matching

In Java, use Pattern to compile a regular expression and Matcher to find matches in text. First, create a Pattern object with your regex, then create a Matcher from that pattern and the input string to check for matches or extract data.
📐

Syntax

The Pattern class compiles a regular expression into a pattern that can be reused. The Matcher class applies this pattern to a given input string to find matches.

  • Pattern pattern = Pattern.compile(String regex); - compiles the regex.
  • Matcher matcher = pattern.matcher(CharSequence input); - creates a matcher for the input.
  • matcher.find() - checks if the pattern matches anywhere in the input.
  • matcher.group() - returns the matched substring.
java
import java.util.regex.Pattern;
import java.util.regex.Matcher;

Pattern pattern = Pattern.compile("your-regex");
Matcher matcher = pattern.matcher("input string");

if (matcher.find()) {
    String match = matcher.group();
}
💻

Example

This example shows how to find all words starting with 'a' in a sentence using Pattern and Matcher.

java
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class RegexExample {
    public static void main(String[] args) {
        String text = "An apple a day keeps the doctor away.";
        Pattern pattern = Pattern.compile("\\ba\\w*\\b", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(text);

        while (matcher.find()) {
            System.out.println("Found: " + matcher.group());
        }
    }
}
Output
Found: An Found: apple Found: a Found: away
⚠️

Common Pitfalls

Common mistakes include:

  • Not escaping special regex characters properly.
  • Using matcher.matches() instead of matcher.find(). matches() checks the whole string, while find() looks for any part matching.
  • Recompiling the Pattern inside loops, which is inefficient.
java
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class PitfallExample {
    public static void main(String[] args) {
        String text = "cat, bat, rat";

        // Wrong: Using matches() to find 'bat' inside the string
        Pattern pattern = Pattern.compile("bat");
        Matcher matcher = pattern.matcher(text);
        System.out.println("Using matches(): " + matcher.matches()); // false

        // Right: Using find() to locate 'bat'
        matcher.reset();
        System.out.println("Using find(): " + matcher.find()); // true
    }
}
Output
Using matches(): false Using find(): true
📊

Quick Reference

MethodDescription
Pattern.compile(String regex)Compiles the regex into a pattern object.
pattern.matcher(CharSequence input)Creates a matcher to apply the pattern on input.
matcher.find()Returns true if a subsequence matches the pattern.
matcher.matches()Returns true if the entire input matches the pattern.
matcher.group()Returns the matched substring from the last match.

Key Takeaways

Use Pattern.compile() once to create a reusable regex pattern.
Use Matcher to apply the pattern to input strings and find matches.
Use matcher.find() to search for matches anywhere in the text.
Avoid recompiling patterns inside loops for better performance.
Remember matcher.matches() checks the whole string, not parts.