简体   繁体   English

ReplaceAll和“不替换

[英]ReplaceAll and " doesn't replace

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. 我很困惑为什么第二个if子句不起作用。 I'd like to get a hint, thanks. 我想得到一个提示,谢谢。

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

Because ZERO is a very valid index. 因为ZERO是一个非常有效的索引。 Try this out, 试试这个,

    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." String.indexOf(String str)的文档解释说, “如果字符串参数作为此对象中的子字符串出现,则返回第一个此类子字符串的第一个字符的索引;如果它不作为子字符串出现,返回-1。“ - [link to docs] - [链接到文档]

This can be done as simple as below, as OpenSauce pointed out here . 这可以像下面这样简单地完成,正如OpenSauce这里指出的那样。

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

Useful links: 有用的链接:

You don't need to check the substring exists, the replace and replaceAll methods are no-ops if the substring is not found. 您不需要检查子字符串是否存在,如果找不到子字符串,则replacereplaceAll方法都是no-ops。 Since you're not looking for regexes, you can also use replace instead 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. 由于你不是在寻找正则表达式,你也可以使用replace而不是replaceAll - 它会更有效率,如果你还想检查碰巧包含正则表达式特殊字符的其他字符串,也不会让你感到惊讶。

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

note that replace does indeed replace all matches, like you want. 请注意, replace确实会替换所有匹配,就像您想要的那样。 The difference between replace and replaceAll is whether the arg is interpreted as a regex or not. replacereplaceAll之间的区别在于arg是否被解释为正则表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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