Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 790
parul71625 Avatar asked Dec 23 '22 23:12

parul71625


2 Answers

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);
like image 155
ajb Avatar answered May 03 '23 23:05

ajb


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)

like image 22
Pavneet_Singh Avatar answered May 03 '23 23:05

Pavneet_Singh