Regex replacement and limits
What you will learn
Regex replacement has two separate languages: the search pattern and the replacement template. Quote user-provided literal text in the correct context. Keep patterns simple and bounded; Java regex does not offer a built-in per-match time limit.
- Distinguish literal replacement from group substitution.
- Quote search text and replacement text separately.
- Apply length and structural limits to a validation rule.
Each example is a complete Main.java file. Use a fresh directory, javac --release 21 Main.java, then java Main. No external dependencies.
Reorder captured fields
import java.util.*;import java.util.regex.*;import java.nio.*;import java.nio.charset.*;import java.io.*;import javax.xml.XMLConstants;import javax.xml.parsers.*;import org.xml.sax.*;import org.xml.sax.helpers.DefaultHandler;import org.w3c.dom.*;public class Main { public static void main(String[] args) throws Exception { var p = Pattern.compile("(?<family>[A-Za-z]+), (?<given>[A-Za-z]+)"); System.out.println(p.matcher("Lee, Ada; Park, Min").replaceAll("${given} ${family}")); System.out.println(p.matcher("Lee, Ada; Park, Min").replaceFirst("${given} ${family}")); }}Expected output:
Ada Lee; Min ParkAda Lee; Park, MinNamed captures are interpreted in the replacement template.
Replacement templates
replaceAll replaces all matches; replaceFirst replaces the first. In a regex replacement, $1 means capture 1 and ${name} means a named capture. Backslashes can escape replacement characters. Pattern.quote protects text interpreted as a search pattern; Matcher.quoteReplacement protects text used as a replacement. For plain substring substitution, String.replace is simpler.
Bound work before matching
Use reviewed fixed patterns, explicit length limits, and bounded repetitions. Ambiguous overlapping repetitions may force excessive backtracking on nonmatching input. Do not accept user-supplied regex patterns in an ordinary validation endpoint. Java Pattern has no universal timeout. A future cancellation request does not guarantee a stuck matcher stops; use a suitable linear-time engine or isolation for genuinely untrusted patterns. The length cap alone is not proof of safe runtime.
Split and output context
Pattern.split and String.split use regex delimiters. A zero limit discards trailing empty fields; a negative limit retains them. This is not a CSV parser: quoted separators and escaped values need format-aware parsing. Regex quoting is not HTML, XML, JSON or SQL escaping.
Preserve literal dollar and dot
import java.util.*;import java.util.regex.*;import java.nio.*;import java.nio.charset.*;import java.io.*;import javax.xml.XMLConstants;import javax.xml.parsers.*;import org.xml.sax.*;import org.xml.sax.helpers.DefaultHandler;import org.w3c.dom.*;public class Main { public static void main(String[] args) throws Exception { String needle = "a.b"; String value = "$5"; String input = "a.b axb a.b"; System.out.println(Pattern.compile(Pattern.quote(needle)).matcher(input).replaceAll(Matcher.quoteReplacement(value))); System.out.println(input.replace(needle, value)); }}Expected output:
$5 axb $5$5 axb $5Both methods preserve the literal dot and dollar; the regex uses two different quoting helpers.
Keep empty fields
import java.util.*;import java.util.regex.*;import java.nio.*;import java.nio.charset.*;import java.io.*;import javax.xml.XMLConstants;import javax.xml.parsers.*;import org.xml.sax.*;import org.xml.sax.helpers.DefaultHandler;import org.w3c.dom.*;public class Main { public static void main(String[] args) throws Exception { System.out.println(Arrays.toString(Pattern.compile(",").split("A,,B,", -1))); System.out.println(Arrays.toString(Pattern.compile(",").split("A,,B,", 0))); }}Expected output:
[A, , B, ][A, , B]The negative limit preserves trailing empty fields; neither call understands CSV quoting.
Bound a simple product code
import java.util.*;import java.util.regex.*;import java.nio.*;import java.nio.charset.*;import java.io.*;import javax.xml.XMLConstants;import javax.xml.parsers.*;import org.xml.sax.*;import org.xml.sax.helpers.DefaultHandler;import org.w3c.dom.*;public class Main { public static void main(String[] args) throws Exception { var p = Pattern.compile("[A-Z]{2}-[0-9]{1,4}"); for (String s : List.of("AB-12", "AB-12345", "A".repeat(100))) { System.out.println(s.length() <= 7 && p.matcher(s).matches()); } }}Expected output:
truefalsefalseThe length check short-circuits before regex work; the fixed pattern has no nested ambiguous repetitions.
Common mistakes
Pattern.quote is not suitable for escaping a replacement template. Do not benchmark dangerous expressions by feeding huge adversarial strings to the lesson runner. Do not assume replaceAll handles literal dollar values without quoting.
Practice
Replace the literal marker price? in price? / price? with the literal value $9. Keep the regex search and replacement independently quoted.
Expected output:
$9 / $9Compare your answer with the manual practice criteria.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Regex replacement and limits — knowledge check
Original regex, text and structured data questions. Java 21-compatible scope.
What protects a literal search term?
What protects a literal dollar in replacement?
What does replaceFirst change?
What split limit preserves trailing empties?
Which is a safer validation design?