![](/img/trans.png)
[英]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.