为了账号安全,请及时绑定邮箱和手机立即绑定

有选择地替换子字符串

有选择地替换子字符串

慕容3067478 2023-04-13 14:09:46
String str = "hdfCity1kdCity12fsd". 我只想替换City1而不Goa替换上面字符串City1中的序列。City1X我尝试使用替换功能。str = str.replace("City1", "Goa")但结果是str = "hdfGoakdGoa2fsd"如何进行这种选择性替换?得到这个想要的结果str = "hdfGoakdCity12fsd";//solution: str.replaceAll("(?<!\\d)City1(?!\\d)", "Goa");抱歉让我的案子不清楚
查看完整描述

5 回答

?
扬帆大鱼

TA贡献1799条经验 获得超9个赞

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


String str = "City1 is beautiful than City12";

str = str.replaceFirst("City1", "Goa");

System.out.println(str);

将输出:


Goa is beautiful than City12

除此之外,您可以使用更复杂的正则表达式来匹配您的确切情况



查看完整回答
反对 回复 2023-04-13
?
胡子哥哥

TA贡献1825条经验 获得超6个赞

您可以使用 replaceFirst() 或 replaceAll() 方法,但如果您想在中间替换,您可以找到您要查找的事件(此处的一个示例:Occurrences of substring in a string)

使用返回的索引生成 2 个子字符串:第一部分保持不变,在第二部分中,必须替换第一个出现的位置 (replaceFirst())

最后:连接两个子串。


查看完整回答
反对 回复 2023-04-13
?
蓝山帝景

TA贡献1843条经验 获得超7个赞

您可以使用以下方法replaceFirst(regex, replacement):


 String str = "City1 is beautiful than City12";

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


查看完整回答
反对 回复 2023-04-13
?
幕布斯7119047

TA贡献1794条经验 获得超8个赞

如果它只是关于第一部分,你也可以使用 substring 方法。例子:


String str = "City1 is beautiful than City12";

str = "Goa" + str.substring(5);


查看完整回答
反对 回复 2023-04-13
?
哆啦的时光机

TA贡献1779条经验 获得超6个赞

如果您确定 City1 除了空格之外不会有任何字符,您可以使用:


String str = "City1 is beautiful than than City12";

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

System.out.println(str);

与您的相同,但在替换字符串和新字符串的末尾有额外的空间


查看完整回答
反对 回复 2023-04-13
  • 5 回答
  • 0 关注
  • 130 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信