简体   繁体   中英

Replace a substring at a particular position in a string in Java

Following is my string variable :

String str = "Home(om), Home(gia)";

I want to replace the substring om present between () with tom .

I am able to find the index of () in which om is present, but the following will not work :

int i1 = str.indexOf("(");
int i2 = str.indexOf(")");

str = str.replace(str.substring(i1+1,i2),"tom");

I require the result as Home(tom), Home(gia) .

How to do this?

I would not use any replace() method if you know the indexes of the substring you want to replace. The problem is that this statement:

str = str.replace(str.substring(someIndex, someOtherIndex), replacement);

first computes the substring, and then replaces all occurrences of that substring in the original string. replace doesn't know or care about the original indexes.

It's better to just break up the string using substring() :

int i1 = str.indexOf("(");
int i2 = str.indexOf(")");

str = str.substring(0, i1+1) + "tom" + str.substring(i2);

You can use regex with replaceAll

String str = "Home(om)";

str = str.replaceAll("[(].*[)]", "(tom)");
System.out.println(str);

Output:

Home(tom)

[(] : look for (

.* : capture all except line break mean \\n\\r

[)] : look for )

UPDATE :

You can use replaceFirst with non-greedy quantifier ?

    String str = "Home(om), Home(gia)";

    str = str.replaceFirst("([(](.*?)[)])", "(tom)");
    System.out.println(str);

Output:

Home(tom), Home(gia)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM