Home > front end >  Replace a String between two Strings and Boundary words also
Replace a String between two Strings and Boundary words also

Time:08-06

I want to replace string variable text between two words and replace the boundary words themselves. Similar to this question, however I want to replace between &firstString and &endString with newText .

Replace a String between two Strings

Input:

abcd&firstString={variableText}&endStringxyz

Output:

abcdnewTextxyz

I could just do two str.replaceAll(&firstString) and str.replaceAll(&secondString). However, is it possible to do in one line of code changing maybe this code solution?

String newstr = str.replaceAll("(&firstString=)[^&]*(&endString=)", "$1foo$2");

CodePudding user response:

String replacement = "newText";
String text = "abcd&firstString={currentText}&secondStringxyz";
String result = text.replaceAll("&firstString=\\{.*?\\}&secondString",replacement);

System.out.println(result);

prints

abcdnewTextxyz
  • Related