How to replace a substring of a string [duplicate]

2020-01-29 05:19发布

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.

7条回答
闹够了就滚
2楼-- · 2020-01-29 05:37

2 things you should note:

  1. Strings in Java are immutable to so you need to store return value of thereplace method call in another String.
  2. You don't really need a regex here, just a simple call to String#replace(String) will do the job.

So just use this code:

String replaced = string.replace("abcd", "dddd");
查看更多
ら.Afraid
3楼-- · 2020-01-29 05:46

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceAll. Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if desired.

from javadoc.

查看更多
你好瞎i
4楼-- · 2020-01-29 05:58

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
查看更多
够拽才男人
5楼-- · 2020-01-29 06:00

By regex i think this is java, the method replaceAll() returns a new String with the substrings replaced, so try this:

String teste = "abcd=0; efgh=1";

String teste2 = teste.replaceAll("abcd", "dddd");

System.out.println(teste2);

Output:

dddd=0; efgh=1
查看更多
淡お忘
6楼-- · 2020-01-29 06:01

In javascript:

var str = "abcdaaaaaabcdaabbccddabcd";
document.write(str.replace(/(abcd)/g,"----"));
//example output: ----aaaaa----aabbccdd----

In other languages, it would be something similar. Remember to enable global matches.

查看更多
成全新的幸福
7楼-- · 2020-01-29 06:01

You are probably not assigning it after doing the replacement or replacing the wrong thing. Try :

String haystack = "abcd=0; efgh=1";
String result = haystack.replaceAll("abcd","dddd");
查看更多
登录 后发表回答