java ReplaceAll 和 " 不更换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6069475/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 14:11:20  来源:igfitidea点击:

ReplaceAll and " doesn't replace

javastring

提问by Hannelore

Can anyone point me out how the first if works and the second doesn't? I'm puzzled why the second if-clause isn't working. I'd like to get a hint, thanks.

谁能指出我第一个 if 是如何工作的,而第二个则没有?我很困惑为什么第二个 if 子句不起作用。求指点,谢谢。

String msg = o.getTweet();
        if (msg.indexOf("&") > 0) {
            msg = msg.replaceAll("&", "&");// vervangt & door &
        }
        if (msg.indexOf(""") > 0) {
            msg = msg.replaceAll(""", "aa"); //vervangt " door "
        }

回答by Adeel Ansari

Because ZEROis a very validindex. Try this out,

因为ZERO是一个非常有效的索引。试试这个,

    String msg = o.getTweet();
    if (msg.indexOf("&") != -1) {
        msg = msg.replaceAll("&", "&");// vervangt & door &
    }
    if (msg.indexOf(""") != -1) {
        msg = msg.replaceAll(""", "aa"); //vervangt " door "
    }

Explanation:

解释:

The documentation of String.indexOf(String str)explains that, "if the string argument occurs as a substring within this object, then the index of the first character of the first such substring is returned; if it does not occur as a substring, -1 is returned."- [link to docs]

的文档String.indexOf(String str)解释说,“如果字符串参数作为此对象中的子字符串出现,则返回第一个此类子字符串的第一个字符的索引;如果它不作为子字符串出现,则返回 -1。” - [文档链接]

This can be done as simple as below, as OpenSaucepointed out here.

正如OpenSauce此处指出的那样,这可以像下面一样简单地完成。

msg = msg.replace("&", "&").replace(""", "\"");

Useful links:

有用的链接:

回答by OpenSauce

You don't need to check the substring exists, the replaceand replaceAllmethods are no-ops if the substring is not found. Since you're not looking for regexes, you can also use replaceinstead of replaceAll- it will be somewhat more efficient, and won't surprise you if you also want to check for other strings which happen to contain regex special chars.

您不需要检查子字符串是否存在,如果未找到子字符串,则replacereplaceAll方法是无操作的。由于您不是在寻找正则表达式,因此您也可以使用replace代替replaceAll- 它会更有效率,并且如果您还想检查其他碰巧包含正则表达式特殊字符的字符串,您也不会感到惊讶。

msg = msg.replace("&", "&").replace(""", "\"");

note that replacedoes indeed replace allmatches, like you want. The difference between replaceand replaceAllis whether the arg is interpreted as a regex or not.

请注意,replace确实会替换所有匹配项,就像您想要的那样。replace和之间的区别在于replaceAllarg 是否被解释为正则表达式。