How to replace a substring of a string

MichalB picture MichalB · May 23, 2013 · Viewed 220.7k times · Source

Assuming I have a String string like this:

"abcd=0; efgh=1"

and I want to replace "abcd" by "dddd". I have tried to do such thing:

string.replaceAll("abcd","dddd");

It does not work. Any suggestions?

EDIT: To be more specific, I am working in Java and I am trying to parse the HTML document, concretely the content between <script> tags. I have already found a way how to parse this content into a string:

 if(tag instanceof ScriptTag){
        if(((ScriptTag) tag).getStringText().contains("DataVideo")){
            String tagText = ((ScriptTag)tag).getStringText();
      }
}

Now I have to find a way how to replace one substring by another one.

Answer

Alper picture Alper · May 23, 2013

You need to use return value of replaceAll() method. replaceAll() does not replace the characters in the current string, it returns a new string with replacement.

  • String objects are immutable, their values cannot be changed after they are created.
  • You may use replace() instead of replaceAll() if you don't need regex.
    String str = "abcd=0; efgh=1";
    String replacedStr = str.replaceAll("abcd", "dddd");

    System.out.println(str);
    System.out.println(replacedStr);

outputs

abcd=0; efgh=1
dddd=0; efgh=1