Pattern Matching with Regex
Part of the Logic & Flow section of Coddy's Java journey — lesson 47 of 59.
The Pattern and Matcher classes provide powerful tools for regex operations in Java. First, let's understand how to use them:
Create a pattern using Pattern.compile():
Pattern pattern = Pattern.compile("cat");
// Creates a pattern to find "cat"Create a matcher for your text:
String text = "The cat and dog";
Matcher matcher = pattern.matcher(text);
// Creates a matcher for the textNow you can find matches using matcher.find():
while (matcher.find()) {
System.out.println("Found at: " + matcher.start());
}After executing the above code, the output is: Found at: 4
Understanding the methods:
<b>matcher.find()</b>- Searches for the next occurrence of the pattern in the text- Returns
trueif a match is found - Returns
falseif no more matches exist - This is why we use it in a
whileloop - to find all occurrences
- Returns
<b>matcher.start()</b>- Returns the starting index (position) of the last match found byfind()- In our example, "cat" starts at index 4 in "The cat and dog"
- Must be called after a successful
find()
Example with multiple matches:
Pattern pattern = Pattern.compile("cat");
Matcher matcher = pattern.matcher("cat and cat");
while (matcher.find()) {
System.out.println("Found at: " + matcher.start());
}
// Output:
// Found at: 0
// Found at: 8Challenge
EasyCreate a method named findWords that takes two arguments:
- A String (
text) to search in - A String (
word) to find
The method should:
- Use Pattern and Matcher to find all occurrences of the word
- Return a string containing the positions where the word was found
- Positions should be separated by spaces
Return messages should be:
- If any input is null: return "Invalid input"
- If word not found: return "Not found"
- If found: return positions (e.g., "4 10 15")
Cheat sheet
The Pattern and Matcher classes provide powerful tools for regex operations in Java.
Create a pattern using Pattern.compile():
Pattern pattern = Pattern.compile("cat");
// Creates a pattern to find "cat"Create a matcher for your text:
String text = "The cat and dog";
Matcher matcher = pattern.matcher(text);
// Creates a matcher for the textFind matches using matcher.find():
while (matcher.find()) {
System.out.println("Found at: " + matcher.start());
}Key methods:
<b>matcher.find()</b>- Searches for the next occurrence of the pattern- Returns
trueif found,falseif no more matches - Use in a loop to find all occurrences
- Returns
<b>matcher.start()</b>- Returns the starting index of the last match found- Call after a successful
find()
- Call after a successful
Try it yourself
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Main {
public static String findWords(String text, String word) {
// Write your code here
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String text = scanner.nextLine();
String word = scanner.nextLine();
if (text.equals("null")) text = null;
if (word.equals("null")) word = null;
System.out.println(findWords(text, word));
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays2HashMap Part 1
What is a HashMap?Declare a HashMapAccessing ValuesCheck If Key ExistsModifying DictionariesRecap - HashMap5HashSet Part 2
Math - Union of HashSetsMath - Intersection of HashSetMath - Set DifferenceMath - Symmetric DifferenceSubsets and SupersetsIterating Over Sets8Advanced String Operations
StringBuilder BasicsStringBuffer IntroductionRegular Expressions BasicsPattern Matching with RegexString TokenizerAdvanced String Formatting