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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With