简体   繁体   中英

java regex to escape oracle sql special characters

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 $0 to refer to the value of the matched expression:

myString.replaceAll(myPattern, "\\\\$0")

For example,

System.out.println("abcdef".replaceAll("[a-c]", "\\\\$0"));

produces

\a\b\cdef

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.

If all you want to do is escape SQL characters I would recommend using PreparedStatements in Java rather than trying to construct your own escaper.

That being said, it would be possible to do so with regex but it wouldn't be easy

You need to capture the pattern with parenthesis like so

(a)(b)(c)

And letter you can refer to them by a $+the ordinal of the parentheses pair

For example, if you apply the replacement pattern

$1\$2$3

it will give

a\bca\bc

In java this become

String resultString = subjectString.replaceAll("(a)(b)(c)", "$1\\\\$2$3");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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