Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add escape "\" in front of special character for a string

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

like image 798
Visahan Avatar asked Sep 10 '15 09:09

Visahan


2 Answers

There is actually a better way of doing this in a sleek manner.

String REGEX = "[\\[+\\]+:{}^~?\\\\/()><=\"!]";

StringUtils.replaceAll(inputString, REGEX, "\\\\$0");
like image 177
Tauseef Rahaman Avatar answered Oct 05 '22 23:10

Tauseef Rahaman


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.

like image 23
Laurentiu L. Avatar answered Oct 05 '22 23:10

Laurentiu L.