Issue
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
.
href="https://stackoverflow.com/questions/10403639/replace-a-string-between-two-strings">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");
Solution
String replacement = "newText";
String text = "abcd&firstString={currentText}&secondStringxyz";
String result = text.replaceAll("&firstString=\\{.*?\\}&secondString",replacement);
System.out.println(result);
prints
abcdnewTextxyz
Answered By - WJS
Answer Checked By - Katrina (JavaFixing Volunteer)