The Pattern and Matcher classes in Advance Java are part of java.util.regex. They provide powerful regular expression support for searching, matching, and extracting text patterns.
In Java, regular expressions are first compiled using the Pattern class. The compiled pattern is then used by a Matcher to perform operations on character sequences.
// Import regex package
import java.util.regex.*;
public class PatternDemo {
public static void main(String[] args) {
// Compile a regular expression
Pattern pattern = Pattern.compile("java");
// Input text where pattern will be searched
Matcher matcher = pattern.matcher("I love java programming");
// Check if pattern exists
while (matcher.find()) {
System.out.println("Match found at index: " + matcher.start());
}
}
}
Match found at index: 7
The find() method scans the input string and locates the word java. The start() method returns the starting index of the match.
Simulate the Java Matcher engine here. Change the Pattern or Text below to see matches update instantly.
Pattern objects for better performancematches() only when validating full input