Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReplaceAll and " doesn't replace

Tags:

java

string

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.

String msg = o.getTweet();
        if (msg.indexOf("&") > 0) {
            msg = msg.replaceAll("&", "&");// vervangt & door &
        }
        if (msg.indexOf(""") > 0) {
            msg = msg.replaceAll(""", "aa"); //vervangt " door "
        }
like image 467
Hannelore Avatar asked May 20 '11 08:05

Hannelore


People also ask

What is replaceAll \\ s+?

\\s+ --> replaces 1 or more spaces. \\\\s+ --> replaces the literal \ followed by s one or more times.

What is replaceAll \\ s in Java?

Java String replaceAll() The Java String class replaceAll() method returns a string replacing all the sequence of characters matching regex and replacement string.

Does replaceAll replace original string?

The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function to be called for each match. The original string is left unchanged.


2 Answers

Because ZERO is a very valid index. 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." - [link to docs]

This can be done as simple as below, as OpenSauce pointed out here.

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

Useful links:

  • String indexOf() docs
  • String replace() docs
  • String replaceAll() docs
like image 98
Adeel Ansari Avatar answered Oct 04 '22 01:10

Adeel Ansari


You don't need to check the substring exists, the replace and replaceAll methods are no-ops if the substring is not found. 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.

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

note that replace does indeed replace all matches, like you want. The difference between replace and replaceAll is whether the arg is interpreted as a regex or not.

like image 44
OpenSauce Avatar answered Oct 04 '22 02:10

OpenSauce