0Pricing
Java Academy · Lesson

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

  1. Compiling Patterns
  2. Finding and Matching
  3. Capturing Groups
  4. Replacing with Regex
← Back to Java Academy