Shashi
Shashi

Reputation: 15273

javaregex - replace multiple occurrances of same pattern

I have this simple program where I am trying to replace multiple occurrences of $P_NAME$ with a string.

public static void replaceAllTest() {
    String textBanner = "This advertisement on $P_NAME$ will make the $P_NAME$ very popular";               
    Pattern replace = Pattern.compile("\\$(.*)\\$");
    Matcher matcherValue = replace.matcher(textBanner);
    String updatedValue = matcherValue.replaceFirst("DotCom");
    System.out.println(updatedValue);
}

I expect the output to be This advertisement on DotCom will make the DotCom very popular but the output I get This advertisement on DotCom very popular. Basically the replaceAll is removing all text till the next occurrence of the pattern.

Please help.

Upvotes: 2

Views: 160

Answers (1)

Tunaki
Tunaki

Reputation: 137104

You need to use a non-greedy regular expression with \\$(.*?)\\$:

public static void replaceAllTest() {
    String textBanner = "This advertisement on $P_NAME$ will make the $P_NAME$ very popular";               
    Pattern replace = Pattern.compile("\\$(.*?)\\$"); // <-- non-greedy here with "?"
    Matcher matcherValue = replace.matcher(textBanner);
    String updatedValue = matcherValue.replaceAll("DotCom"); // <-- replaceAll to replace all matches
    System.out.println(updatedValue);
}

Upvotes: 1

Related Questions