Replace a String between two Strings

前端 未结 6 1933
说谎
说谎 2020-12-07 00:32

Let\'s say we have something like:

&firstString=someText&endString=OtherText

And I would like to replace \"someText\" with somethin

相关标签:
6条回答
  • 2020-12-07 01:13
    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
    
    0 讨论(0)
  • 2020-12-07 01:15

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

    String newstr = str.replaceAll("(&firstString=)[^&]*(&endString=)", "$1foo$2");
    
    0 讨论(0)
  • 2020-12-07 01:16

    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);
     }
    
    0 讨论(0)
  • 2020-12-07 01:29

    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);
    }
    
    0 讨论(0)
  • 2020-12-07 01:30

    just replacing the whole &firstString=someText& since this includes the outer barriers which I assume to be URL related?

    0 讨论(0)
  • 2020-12-07 01:34

    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);
    
    0 讨论(0)
提交回复
热议问题