Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
112 views
in Technique[技术] by (71.8m points)

java - Replace a String between two Strings

Let's say we have something like:

&firstString=someText&endString=OtherText

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 ..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...