Course contentsShow
← Java
Lesson 2278 of 2,87044. Regular ExpressionsFree lesson

Replacement with Named Groups

Use ${name} syntax in Matcher.replaceAll() to reference named groups when constructing replacement strings.

Replacement with Named Groups

What you'll learn: How to use named capturing groups in your replacement strings when calling Matcher.replaceAll() for clearer, more maintainable pattern substitutions.

The Core Idea

When you've captured text using named groups in your regex pattern, you can reference those captures in your replacement string using the special syntax ${groupName}. This lets you rearrange, duplicate, or selectively include captured parts when transforming text—without needing to remember numeric group positions.

Think of it like a find-and-replace operation where you've labeled the pieces you want to keep, then reassemble them however you like in the output.

How It Works

After defining named groups with (?<name>...) in your pattern, use ${name} in the replacement string passed to replaceAll(). The matcher substitutes each ${name} with the text that group captured.

import java.util.regex.*;

public class NamedGroupReplacement {
    public static void main(String[] args) {
        String text = "Contact: John Doe at john.doe@example.com";
        
        Pattern pattern = Pattern.compile("(?<first>\\w+) (?<last>\\w+) at (?<email>\\S+)");
        Matcher matcher = pattern.matcher(text);
        
        // Rearrange: last name first, then email
        String result = matcher.replaceAll("${last}, ${first} (${email})");
        System.out.println(result); // Contact: Doe, John (john.doe@example.com)
    }
}

Notice how ${last}, ${first}, and ${email} map directly to the named groups in your pattern. You can reorder them, repeat them, or omit them entirely—whatever your transformation needs.

Why This Matters

Named group replacements make complex substitutions self-documenting. Instead of $2, $1 ($3), you write ${last}, ${first} (${email})—instantly readable six months later.

Key Takeaway: Use ${groupName} syntax in Matcher.replaceAll() to reference named capturing groups, making your replacement logic clear and maintainable.