javaregex - 替换相同模式的多个出现

时间:2016-03-02 14:44:58

标签: java regex

我有这个简单的程序,我试图用字符串替换多次出现的$ 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删除所有文本,直到下一次出现模式。

请帮忙。

1 个答案:

答案 0 :(得分:1)

您需要non-greedy regular expression使用public static void main(String[] args) throws IOException { Random random = new Random(); int randomInt = random.nextInt(59); FileReader fr = new FileReader("Common.txt"); BufferedReader reader2 = new BufferedReader(fr); for (int i = randomInt; i <= randomInt + 10; i++) { String line = reader2.readLine(); System.out.println(line); } reader2.close(); }

\\$(.*?)\\$