简体   繁体   中英

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

您可以使用支持正则表达式的String#replaceAll ,如下所示:

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

The easiest to understand way to do it is to search for the delimiters, and cut out a substring between their positions, like this:

String str = "&firstString=someText&endString=OtherText";
String firstDelim = "&firstString=";
int p1 = str.indexOf(firstDelim);
String lastDelim = "&endString=";
int p2 = str.indexOf(lastDelim, p1);   // look after start delimiter    
String replacement = "quick_brown_fox";
if (p1 >= 0 && p2 > p1) {
    String res = str.substring(0, p1+firstDelim.length())
               + replacement
               + str.substring(p2);
    System.out.println(res);
}
yourString.replace("someText", "somethingElse");

EDIT based on clarification

String x = "&firstString=someText&endString=OtherText";
int firstPos = x.indexOf("&firstString=") + "&firstString=".length();
int lastPos = x.indexOf("&endString", firstPos);
String y = x.substring(0,firstPos) + "Your new text" + x.substring(lastPos);
System.out.println(y);

Output:

&firstString=Your new text&endString=OtherText

As I understood the question, you should do something like this, but I'm not sure I totally got what you asked:

yourString = firstString + replacingString + endString;

If you want the "replaced" string:

replacedString = wholeString.substring(0, wholeString.lastIndexOf(endString) - 1);
replacedString = tempString.substring(firstString.length() + 1);

This solution checks that we're not going of the end of the string and will do it for multiple occurrences.

 int startIndex = text.indexOf(startDelim);
 while (startIndex > -1)
 {
    int endIndex = text.indexOf(endDelim, startIndex);
    String endPart = "";

    if ((endIndex + endDelim.length()) < text.length())
       endPart = text.substring(endIndex + endDelim.length());

    text = text.substring(0, startIndex) + replacementText + endPart;
    startIndex = text.indexOf(startDelim);
 }

只是替换整个&firstString=someText&因为这包括我认为与URL相关的外部障碍?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM