Using replaceAll( )
The replaceAll( ) method supplied by Matcher lets you perform powerful search and replace operations that use regular expressions.
For example, the following program replaces all occurrences of sequences that begin with "Jon" with "Eric":
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String args[]) {
String str = "Jack Java HTML JavaScript JavaFx";
Pattern pat = Pattern.compile("Ja.*? ");
Matcher mat = pat.matcher(str);
System.out.println("Original sequence: " + str);
str = mat.replaceAll("C# ");
System.out.println("Modified sequence: " + str);
}
}
Original sequence: Jack Java HTML JavaScript JavaFx
Modified sequence: C# C# HTML C# JavaFx
Home
Java Book
Essential Classes
Java Book
Essential Classes
Matcher:
- Regular Expression Processing
- Normal character
- Wildcard character
- Using Wildcards and Quantifiers
- Greedy behavior
- Working with Classes of Characters
- Using replaceAll( )
- Using split( )
- Matcher: appendReplacement(StringBuffer sb,String replacement)
- Matcher.appendTail(StringBuffer sb)
- Matcher: find()
- Matcher: group()
- Matcher: group(int group)
- Matcher: groupCount()
- Matcher: lookingAt()
- Matcher: matches()
- Matcher: replaceAll(String text)
- Matcher: start()