我有一个简单的程序,试图用字符串替换多次出现的$ P_NAME $。

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);
}


我希望输出为This advertisement on DotCom will make the DotCom very popular,但输出为This advertisement on DotCom very popular。基本上replaceAll会删除所有文本,直到下次出现该模式为止。

请帮忙。

最佳答案

您需要将non-greedy regular expression\\$(.*?)\\$一起使用:

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);
}

关于java - Java正则表达式-替换多次出现的相同模式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35750418/

10-13 01:13