[英]Replace a string at particular position with another string without hardcoding in java
[英]Replace a substring at a particular position in a string in Java
以下是我的字符串变量:
String str = "Home(om), Home(gia)";
我想用tom
替换()
之间存在的子字符串om
。
我可以找到存在om
的()
的索引,但是以下操作无效:
int i1 = str.indexOf("(");
int i2 = str.indexOf(")");
str = str.replace(str.substring(i1+1,i2),"tom");
我需要结果为Home(tom), Home(gia)
。
这个怎么做?
如果您知道要替换的子字符串的索引,则不会使用任何replace()
方法。 问题是该语句:
str = str.replace(str.substring(someIndex, someOtherIndex), replacement);
首先计算子字符串,然后替换该子字符串在原始字符串中的所有匹配项。 replace
不知道或不在乎原始索引。
最好使用substring()
分解字符串:
int i1 = str.indexOf("(");
int i2 = str.indexOf(")");
str = str.substring(0, i1+1) + "tom" + str.substring(i2);
您可以将regex与replaceAll
String str = "Home(om)";
str = str.replaceAll("[(].*[)]", "(tom)");
System.out.println(str);
输出:
家(汤姆)
[(]
:寻找(
.*
:捕获所有除换行符\\n\\r
[)]
:寻找)
更新:
您可以将replaceFirst
与非贪婪量词一起使用?
String str = "Home(om), Home(gia)";
str = str.replaceFirst("([(](.*?)[)])", "(tom)");
System.out.println(str);
输出:
家(tom),家(gia)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.