title: Replace special character with an escape preceded special character in Java
body: <p>In my java code, if a string input has got any of the special characters mentioned, that should get preceded by <code>\\</code></p>
  
  <p>Special character set is <code>{+, -, &amp;&amp;, ||, !, (, ), {, },[, ], ^, "", ~, *, ?, :, \}</code>. I tried using <code>String.replaceAll(old,new)</code> but to my surprise its not working, even though I am giving proper values for 'old' and 'new'.</p>
  
  <pre><code>if old=":",new="\:"
  </code></pre>
  
  <p>I put the special chars in a String array, iterated it in a for loop, checked whether it is present in the string, if yes, <code>input.replaceAll(":","\\:")</code>. But its not giving me the intended output. Please help</p>
  
  <pre><code>String[] arr = { "+", "-", "&amp;&amp;", "||", "!", "(", ")", "{", "}",
                  "[", "]", "^", "\"", "~", "*", "?", ":", "\\", "AND", "OR" };
  
      for (int i = 0; i &lt; arr.length; i++) {
  //'search' is my input string
  
          if (search.contains((String) arr[i])) {
  
              String oldString = (String) arr[i];
  
              String newString = new String("\\" + arr[i]);
              search = search.replaceAll(oldString, newString);
              String newSearch = new String(search.replaceAll(arr[i],
                      newString));
  
  
          }
      }
  </code></pre>