Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

`String.replaceAll()`: regex replacement

Replace every match of a regular expression. The example masks values in one specific password-argument format without changing the inputs.

Version: Java SE 21

Syntax

Java SE 21
String replaced = text.replaceAll(regex, replacement); // both arguments: String

replaceAll(String, String) returns the text with every regex match replaced, not just the first. The original string is unchanged. An invalid pattern throws PatternSyntaxException. The replacement has its own syntax: $1 refers to the first capturing group, and \ escapes characters. Use Matcher.quoteReplacement for literal replacement text and Pattern.quote for literal pattern text. If both arguments are literal, use replace(CharSequence, CharSequence) instead.

In the example, \A and \z require a whole-argument match, and (?i) makes the pattern ignore ASCII letter case. Only --password= followed by one or more ASCII letters, ASCII digits, underscores, or hyphens is masked. A separate --password value pair and values such as abc! are left unchanged. This is not general secret redaction: do not pass real passwords on the command line or log this copy. Masking does not erase the original.

Examples

import java.util.Arrays;

public class MaskArgs {
    public static void main(String[] args) {
        String[] original = {"--mode=demo", "--Password=demo_42", "--password=demo-7"};
        String[] copy = new String[original.length];
        String passwordPattern = "(?i)\\A--password=[A-Za-z0-9_-]+\\z";
        boolean originalUnchanged = true;

        for (int i = 0; i < original.length; i++) {
            String before = original[i];
            copy[i] = before.replaceAll(passwordPattern, "--password=***");
            originalUnchanged &= original[i].equals(before);
        }

        System.out.println("COPY: " + Arrays.toString(copy));
        System.out.println("Original unchanged: " + originalUnchanged);
    }
}

Result

COPY: [--mode=demo, --password=***, --password=***]
Original unchanged: true

The program uses dummy values defined in the source. In the expected output, `COPY` contains two masked values and `Original unchanged: true` indicates that the original array entries did not change.

Related lessons

  • Java · Lesson 55 · Advanced · Version: 2

Sources