Replacing with Regex
replaceAll and back references.
Replacing with Regex
Regex is not just for searching; it can transform text. replaceAll swaps every match for a replacement string.
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Main {
public static void main(String[] args) {
Matcher m = Pattern.compile("\\d+").matcher("a1b22c333");
System.out.println(m.replaceAll("#"));
}
}String.replaceAll Shortcut
String.replaceAll(regex, replacement) is a convenient one-liner that compiles the pattern internally.
public class Main {
public static void main(String[] args) {
String cleaned = "hello world again".replaceAll("\\s+", " ");
System.out.println(cleaned);
}
}All lessons in this course
- Compiling Patterns
- Finding and Matching
- Capturing Groups
- Replacing with Regex