0

I want to escape all the special characters in string. Have used the below code.

 public static void main(String[] args) { // TODO Auto-generated method
              String search = "Helo world!@#$%^&*()";
              String regEx = "([^a-zA-Z0-9])";
              Pattern escape = Pattern.compile(regEx);
              String escapeChar = "\\\\$1";
              String value = escape.matcher(search).replaceAll(escapeChar);
              System.out.println(value);
       }

And i'm getting the below output which is not something have wanted.

output: Helo world\!\@\#\$\%\^\&\*\(\)\

Can someone please help me to correct here.

Andremoniy
  • 34,031
  • 20
  • 135
  • 241
Mahendra M
  • 11
  • 2
  • 1
    What are you expecting to output? – Jim Garrison Feb 04 '17 at 17:03
  • It should escape special characters and my final output should like the same as my search string i. e Helo world!@#$%^&*() – Mahendra M Feb 04 '17 at 17:25
  • your current code's output is `Helo\ world\!\@\#\$\%\^\&\*\(\)` not the one you showed , and i guess you want this `([^a-zA-Z0-9\\s])` – Pavneet_Singh Feb 04 '17 at 17:29
  • Hi Pavneet, have tried as you suggested ([^a-zA-Z0-9\\s]) but still i see the below output Helo world\!\@\#\$\%\^\&\*\(\) – Mahendra M Feb 04 '17 at 17:34
  • `*() ` are also special characters , you can add those in you match `([^a-zA-Z0-9\\s()*])` , although if there are any other edge cases then provide the details with expected output – Pavneet_Singh Feb 04 '17 at 17:35
  • I have used the pattern here in such a way that other than small case letter a-z or capital case letters A-Z or numbers 0-9, whatever comes i mean special characters or something then i need to escape those use it as a literal string as it is. – Mahendra M Feb 04 '17 at 17:42
  • _"It should escape special characters and my final output should like the same as my search string"_ -- sorry, this does not make sense. Why would you expect the output to be the same as the input? – Jim Garrison Feb 04 '17 at 17:46
  • i mean in my case, i'm hitting the service with request which contains one of the String including special characters and because of which it is failing. so i though will escape those special characters and send it to the service call. for ex for '$' it is failing now and i fixed it like replacing '\\$' so now its successful and able to save like abc$$ and retrieve the same. Likewise i wanted to check for all the special chars using regex. – Mahendra M Feb 04 '17 at 18:04
  • `search = Pattern.quote(search);` – Wiktor Stribiżew Feb 04 '17 at 20:11

0 Answers0