首页 > 解决方案 > 选择性地替换子字符串

问题描述

String str = "hdfCity1kdCity12fsd". 

我只想替换City1而不Goa替换上面字符串中的City1序列。City1X

我尝试使用替换功能。

str = str.replace("City1", "Goa")

但结果是

str = "hdfGoakdGoa2fsd"

如何进行这种选择性替换?得到这个想要的结果

str = "hdfGoakdCity12fsd";//solution: str.replaceAll("(?<!\\d)City1(?!\\d)", "Goa");

抱歉让我的案子不清楚

谢谢@TiiJ7

标签: javastringreplace

解决方案


在您的情况下,您可以使用replaceFirst(). 这只会替换匹配字符串的第一次出现:

String str = "City1 is beautiful than City12";
str = str.replaceFirst("City1", "Goa");
System.out.println(str);

将输出:

Goa is beautiful than City12

除此之外,您可以使用更复杂的正则表达式来匹配您的确切情况,例如参见这个答案


推荐阅读