Search code examples
javaregexstringreplacereplaceall

Can we replace a specific part of a string literal using any predefined function and regex


I want to replace "&" with a random word "$d" in a given sentence. Can we replace only those words which start with & and are followed by a single character and a space?

Example:-

Input:-

Two literals are &a and &b and also check &abc and &bac here.

Output:-

Two literals are $da and $db and also check &abc and &bac here.

In the above example in input, the only words that should be replaced are &a and &b(not the complete word should be replaced, only just the '&' in both the words) because these two random words start with & and are followed by a single character and a space.

In the case of the replaceAll() function, it replaces the entire word when I used regex:-

String str="Two literals are &a and &b and also check &abc and &bac here.";

str = str.replaceAll("\\&[a-zA-Z]{1}\\s", "\\$d");

System.out.println(str);

//output for this:-Two literals are $d and $d and also check &abc and &bac here.

//expected output:-Two literals are $da and $db and also check &abc and &bac here.

Solution

  • The correct code for this would be

    str.replaceAll("&([a-zA-Z]\\s)", "\\$d$1")
    

    This is an example of backreferencing captured groups in regex, and a here is a nice reference for it. Additionally, here's a relevant StackOverflow question about it.

    Essentially, the match inside the parentheses ([a-zA-Z]\\s) matches a single letter and a space. The value of this match can be referenced with $1 since it is of capturing group 1.

    So we replace &(a ) with $d(a ) (brackets here to demonstrate what is captured). Credit to u/rzwitserloot for reminding me that OP wants $ not &.