在两个字符串之间替换字符串 [英] Replace a String between two Strings
问题描述
假设我们有类似的内容:
Let's say we have something like:
&firstString=someText&endString=OtherText
我想用其他东西替换someText。考虑到我不知道someText可能是什么(任何字符串)这一事实,最好的方法是什么,我所知道的是它将被& firstString =和& endString =
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=
编辑:抱歉看起来这还不够清楚。我不知道someText可能是什么,我唯一的信息是它介于& firstString =和& endString =
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 ..
推荐答案
你可以使用 String#replaceAll that像这样支持正则表达式:
You can use String#replaceAll that has support for regex like this:
String newstr = str.replaceAll("(&firstString=)[^&]*(&endString=)", "$1foo$2");
这篇关于在两个字符串之间替换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!