1. Create and Use a Pattern
This program demonstrates how to create a Pattern object using Pattern.compile(). The pattern defines a regular expression that can be used for matching text. Here, the pattern checks for one or more digits.
import java.util.regex.Pattern;
public class PatternExample {
public static void main(String[] args) {
String input = "Java 123 Programming";
Pattern pattern = Pattern.compile("\\d+");
System.out.println("Pattern: " + pattern.pattern());
System.out.println("Input: " + input);
}
}Output:
Pattern: \d+
Input: Java 123 Programming
2. Match Text Using Matcher
This program demonstrates how the Matcher class searches text using a Pattern. The find() method searches for the next matching sequence in the input. It displays every number found in the given string.
import java.util.regex.*;
public class MatcherExample {
public static void main(String[] args) {
String input = "Java 123 and Python 456";
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
System.out.println("Matched: " + matcher.group());
}
}
}Output:
Matched: 123
Matched: 456
3. Check Complete String Using matches()
This program demonstrates the matches() method of the Matcher class. The matches() method returns true only when the entire input matches the pattern. Here, the pattern checks whether the complete input contains only digits.
import java.util.regex.*;
public class MatcherMatchesExample {
public static void main(String[] args) {
String input = "12345";
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(input);
System.out.println("Input: " + input);
System.out.println("Matches: " + matcher.matches());
}
}Output:
Input: 12345
Matches: trueCode language: JavaScript (javascript)
4. Replace Matching Text Using Matcher
This program demonstrates the replaceAll() method of the Matcher class. It searches for all digits using a Pattern and replaces them with *. The resulting string is then displayed.
import java.util.regex.*;
public class MatcherReplaceExample {
public static void main(String[] args) {
String input = "Java 123 Programming 456";
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(input);
String result = matcher.replaceAll("*");
System.out.println("Input: " + input);
System.out.println("Output: " + result);
}
}Output:
Input: Java 123 Programming 456
Output: Java * Programming *
