猿问

有选择地替换子字符串

String str = "hdfCity1kdCity12fsd". 

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


我尝试使用替换功能。


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

但结果是


str = "hdfGoakdGoa2fsd"

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


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

抱歉让我的案子不清楚


慕容3067478
浏览 131回答 5
5回答

扬帆大鱼

在您的情况下,您可以使用replaceFirst(). 这只会替换您匹配的字符串的第一次出现:String str = "City1 is beautiful than City12";str = str.replaceFirst("City1", "Goa");System.out.println(str);将输出:Goa is beautiful than City12除此之外,您可以使用更复杂的正则表达式来匹配您的确切情况

胡子哥哥

您可以使用 replaceFirst() 或 replaceAll() 方法,但如果您想在中间替换,您可以找到您要查找的事件(此处的一个示例:Occurrences of substring in a string)使用返回的索引生成 2 个子字符串:第一部分保持不变,在第二部分中,必须替换第一个出现的位置 (replaceFirst())最后:连接两个子串。

蓝山帝景

您可以使用以下方法replaceFirst(regex, replacement):&nbsp;String str = "City1 is beautiful than City12";&nbsp;System.out.println(str.replaceFirst("City1", "Goa")); // Goa is beautiful than City12

幕布斯7119047

如果它只是关于第一部分,你也可以使用 substring 方法。例子:String str = "City1 is beautiful than City12";str = "Goa" + str.substring(5);

哆啦的时光机

如果您确定 City1 除了空格之外不会有任何字符,您可以使用:String str = "City1 is beautiful than than City12";str = str.replace("City1 ", "Goa ");System.out.println(str);与您的相同,但在替换字符串和新字符串的末尾有额外的空间
随时随地看视频慕课网APP

相关分类

Java
我要回答