Introduction
Pattern matching finds occurrences of a pattern within text. Essential for search, validation, and text processing.
Method 1: Using indexOf()
public class PatternMatchingBasic {
public static void findPattern(String text, String pattern) {
int index = 0;
while ((index = text.indexOf(pattern, index)) != -1) {
System.out.println("Pattern found at: " + index);
index += pattern.length();
}
}
public static void main(String[] args) {
findPattern("hello world hello", "hello");
}
}
Output:
Pattern found at: 0
Pattern found at: 12
Method 2: Using Regular Expressions
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PatternMatchingRegex {
public static void findPattern(String text, String patternStr) {
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println("Match: " + matcher.group() + " at " + matcher.start());
}
}
public static void main(String[] args) {
findPattern("abc123def456", "[0-9]+");
}
}
Output:
Match: 123 at 3
Match: 456 at 9
Method 3: KMP Algorithm
public class KMPAlgorithm {
public static int[] buildLPS(String pattern) {
int[] lps = new int[pattern.length()];
int len = 0;
int i = 1;
while (i < pattern.length()) {
if (pattern.charAt(i) == pattern.charAt(len)) {
lps[i++] = ++len;
} else if (len != 0) {
len = lps[len - 1];
} else {
lps[i++] = 0;
}
}
return lps;
}
public static void findPattern(String text, String pattern) {
int[] lps = buildLPS(pattern);
int i = 0, j = 0;
while (i < text.length()) {
if (text.charAt(i) == pattern.charAt(j)) {
i++;
j++;
}
if (j == pattern.length()) {
System.out.println("Match at: " + (i - j));
j = lps[j - 1];
} else if (i < text.length() && text.charAt(i) != pattern.charAt(j)) {
if (j != 0) {
j = lps[j - 1];
} else {
i++;
}
}
}
}
}
Frequently Asked Questions
Q1. Which method is fastest?
Answer: KMP for large texts, indexOf() for small strings.
Q2. Overlapping matches?
Answer: Set index correctly in loop.
Q3. Case-insensitive?
Answer: Use toLowerCase() or regex (?i).
Q4. Complex patterns?
Answer: Use regex with special characters.
Q5. Multiple patterns?
Answer: Run each separately or combine in regex.
Q6. Performance?
Answer: indexOf() O(nm), KMP O(n+m).
Q7. Unicode support?
Answer: All methods support Unicode.
Q8. Replace matches?
Answer: Use replaceAll() with regex.
Q9. Count matches?
Answer: Increment counter in loop.
Q10. Real-world use?
Answer: Search engines, text editors, data validation.
Conclusion
Choose based on:
- Simple pattern:
indexOf() - Complex pattern: Regex
- Performance critical: KMP
All have use cases. Master multiple techniques.