user220755 user220755 - 1 year ago 88
Java Question

Replace a String between two Strings

Let's say we have something like:


And I would like to replace "someText" with something else. What is the best way to do this considering the fact that I do not know what someText might be (any string) and all I know is that it will be surrounded with &firstString= and &endString=

Edit: sorry looks like this is not clear enough. I do not know what "someText" might be, the only information I have is that it will be between &firstString= and &endString=

I was thinking about using split multiple times but it sounded ugly ..

Answer Source

You can use String#replaceAll that has support for regex like this:

String newstr = str.replaceAll("(&firstString=)[^&]*(&endString=)", "$1foo$2");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download