java - 选择性地替换子字符串
问题描述
String str = "hdfCity1kdCity12fsd".
我只想替换City1
而不Goa
替换上面字符串中的City1
序列。City1X
我尝试使用替换功能。
str = str.replace("City1", "Goa")
但结果是
str = "hdfGoakdGoa2fsd"
如何进行这种选择性替换?得到这个想要的结果
str = "hdfGoakdCity12fsd";//solution: str.replaceAll("(?<!\\d)City1(?!\\d)", "Goa");
抱歉让我的案子不清楚
谢谢@TiiJ7
解决方案
在您的情况下,您可以使用replaceFirst()
. 这只会替换匹配字符串的第一次出现:
String str = "City1 is beautiful than City12";
str = str.replaceFirst("City1", "Goa");
System.out.println(str);
将输出:
Goa is beautiful than City12
除此之外,您可以使用更复杂的正则表达式来匹配您的确切情况,例如参见这个答案。
推荐阅读
- c# - ES 512 jwt 令牌验证
- treeview - 是否可以重新设置 wxTreeItem 或 wxTreeListItem?
- awk - gawk 中 gensub() 的解释
- swift - 编写 switch 语句以根据数字返回图像而不重复太多代码的最佳方法是什么?
- php - 查询结果到数组字符串
- python-3.x - 为什么每次迭代我的 tqdm 进度条都显示在新行上?
- hugo - 将带有隐私包的 cookie 消息添加到 blogdown 网站
- mysql - 如何在mysql中查找同一列不同行中的两个值之间的差异
- pandas - Pandas - 将缺失的列自动添加到 Dataframe
- reactjs - Redux 状态在状态更新后返回未定义