Replacing with Regex
replaceAll and back references.
Replacing with Regex is a free Java Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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);
}
}replaceFirst
replaceFirst swaps only the first match, leaving later matches untouched.
public class Main {
public static void main(String[] args) {
String s = "cat cat cat".replaceFirst("cat", "dog");
System.out.println(s);
}
}Group References in Replacements
In the replacement string, $1, $2, etc. insert text captured by those groups. This reorders or reformats matched content.
public class Main {
public static void main(String[] args) {
String iso = "30/05/2026".replaceAll("(\\d{2})/(\\d{2})/(\\d{4})", "$3-$2-$1");
System.out.println(iso);
}
}Named Group References
You can also reference named groups in the replacement with ${name}.
public class Main {
public static void main(String[] args) {
String r = "alice@example.com"
.replaceAll("(?<user>\\w+)@(?<host>[\\w.]+)", "${user} at ${host}");
System.out.println(r);
}
}Escaping Dollar and Backslash
Because $ and \ are special in replacements, escape a literal dollar as \$. Matcher.quoteReplacement escapes them for you.
import java.util.regex.Matcher;
public class Main {
public static void main(String[] args) {
String price = "100".replaceAll("\\d+", Matcher.quoteReplacement("$100"));
System.out.println(price);
}
}Computed Replacements with replaceAll Function
Since Java 9, Matcher.replaceAll can take a function, letting you compute each replacement from the match.
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("a1 b2 c3");
String out = m.replaceAll(mr -> String.valueOf(Integer.parseInt(mr.group()) * 10));
System.out.println(out);
}
}Uppercasing Matched Words
The function form shines when the replacement depends on the matched text, such as uppercasing each word.
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Main {
public static void main(String[] args) {
Matcher m = Pattern.compile("\\b\\w").matcher("hello there world");
String title = m.replaceAll(mr -> mr.group().toUpperCase());
System.out.println(title);
}
}appendReplacement and appendTail
For full control, loop with find and build output via appendReplacement then appendTail. This is the classic low-level technique.
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("a1b2");
StringBuilder sb = new StringBuilder();
while (m.find()) {
m.appendReplacement(sb, "[" + m.group() + "]");
}
m.appendTail(sb);
System.out.println(sb);
}
}Backreferences in the Pattern
Backreferences in the pattern (\1) match repeated text, useful for collapsing doubled words during replacement.
public class Main {
public static void main(String[] args) {
String fixed = "the the end end".replaceAll("\\b(\\w+) \\1\\b", "$1");
System.out.println(fixed);
}
}Stripping Unwanted Characters
A frequent use is sanitizing input by replacing everything outside an allowed set with empty.
public class Main {
public static void main(String[] args) {
String digits = "(555) 123-4567".replaceAll("[^0-9]", "");
System.out.println(digits);
}
}Quick Check
In a replacement string for replaceAll, what does $2 mean?
Recap
You transformed text with regex:
replaceAllandreplaceFirstswap matches;Stringoffers shortcuts.$1/${name}insert captured groups in replacements; escape literal$as\$or viaquoteReplacement.- The function form of
replaceAllcomputes replacements from each match. appendReplacement+appendTailgive full manual control.
Frequently asked questions
Is the “Replacing with Regex” lesson free?
Yes — the full text of “Replacing with Regex” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.
What will I learn in “Replacing with Regex”?
replaceAll and back references. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Java Academy?
No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Replacing with Regex” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Java Academy lesson?
Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Compiling Patterns
- Finding and Matching
- Capturing Groups
- Replacing with Regex