I have a simple SQL query where I check whether the query matches any of the fields I have. I'm using LIKE statement for this. One of my field can have special characters and so does the search query. So I'm looking for a solution where I need to an escape "\" in front of the special character.
query = "hello+Search}query"
I need the above to change to
query = "hello\+Search\}query"
Is there a simple way of doing this other than searching for each special character separately and adding the "\". Because if I don't have the escape character I will get the error message
java.util.regex.PatternSyntaxException: Dangling meta character '+' near index 0
Thanks in advance
There is actually a better way of doing this in a sleek manner.
String REGEX = "[\\[+\\]+:{}^~?\\\\/()><=\"!]";
StringUtils.replaceAll(inputString, REGEX, "\\\\$0");
Decide which special characters you want to escape and just call
query.replace("}", "\\}")
You may keep all special characters you allow in some array then iterate it and replace the occurrences as exemplified. This method replaces all regex meta characters.
public String escapeMetaCharacters(String inputString){
final String[] metaCharacters = {"\\","^","$","{","}","[","]","(",")",".","*","+","?","|","<",">","-","&","%"};
for (int i = 0 ; i < metaCharacters.length ; i++){
if(inputString.contains(metaCharacters[i])){
inputString = inputString.replace(metaCharacters[i],"\\"+metaCharacters[i]);
}
}
return inputString;
}
You could use it as query=escapeMetaCharacters(query);
Don't think that any library you would find would do anything more than that. At best it defines a complete list of specialCharacters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With