I want to escape all the special character is an sql query. So i created thi regex:
Pattern p1 = Pattern.compile("\\{ | \\} | \\\\ | \\, | \\& | \\? |"
+ " \\( | \\) | \\[ | \\] | \\- | \\; | \\~ | \\| | \\ $ | "
+ "\\! | \\< | \\> | \\* | \\% | \\_");
Matcher m1=p1.matcher(s);
Now I want it to iterate through all the matches and put an ‘\’ character before it. For example if a string is : aa%aa$aa, I want it to be aa\%aa\$aa. How can i do this?
You can use back reference
$0to refer to the value of the matched expression:For example,
produces
Note the excessive number of slashes in the replacement: I need to pass two backslashes to regexp (the first one escapes the second one), and for each one I must put two in order for the Java to do its own escaping, for the final count of four.