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

6

14

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

Langston answered 10/9, 2015 at 9:47 Comment(2)
What context are you using it in? Why do you use it in a regex? Can you show the context where that error is happening (please edit the question).Hamforrd
Also please add what database you are using.Hamforrd
P
26

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.

Plath answered 10/9, 2015 at 9:53 Comment(4)
OP said "other than searching for each special character separately and adding the \".Hamforrd
Indeed, but there is no better option. I recommend he just keeps track of all special characters he escapes.Plath
You need to init outputString to inputString and not to an empty String, in case no special characters existsPriapitis
Still need this kind of workaround in Java in 2018 :(Hypochondria
N
8

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

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

StringUtils.replaceAll(inputString, REGEX, "\\\\$0");
Northington answered 27/7, 2021 at 9:33 Comment(2)
This method is deprecated in newer versions of commons-lang3 ( my version is 3.12.0 )Lev
commons lang methods is just a null safe replacement for inbuilt string method String.replaceAll(). inputString.replaceAll(REGEX, "\\\\$0") would work too if you ensure inputString is not null.Cochineal
G
2

You need to use \\ to introduce a \ into a string literal; that is you need to escape the \. (A single backslash is used to introduce special characters into a string: e.g. \t is a tab.)

query = "hello\\+Search\\}query" is what you need.

Guy answered 10/9, 2015 at 9:50 Comment(6)
ok, but either way, I need a way to identify the location of the special character such as "+", so I would be able to add that value. My query looks like this "hello+Search}query" I need to find the special characters location to add the escape character.Langston
Simply replace + with \\+, etc.Guy
Or use a prepared statement. It should also be able to handle these special characters.Monanthous
I need a generic method to identify all the special characters in my query, "+" was an example. So I was looking for a solution which is more elegant than looking for each special character and replace it.Langston
@Tom: I agree. Sadly, the OP has not specified the database.Guy
@Langston there isn't a more elegant solution. If you find a library/class that does that, inside you will find a function similar to what i provided.Plath
C
2

I had to do same thing in javascript. I came up with below solution. I think it might help someone.

function escapeSpecialCharacters(s){
 let arr = s.split('');
 arr = arr.map(function(d){
         return d.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\'+d)
       });
 let reg = new RegExp(arr.join('')); 
 return reg;
}

let newstring = escapeSpecialCharacters("hello+Search}query");
Calabria answered 9/5, 2018 at 5:57 Comment(0)
C
0

If you want to use Java 8+ and Streams, you could do something like:

private String escapeSpecialCharacters(String input) {
    List<String> specialCharacters = Lists.newArrayList("\\","^","$","{","}","[","]","(",")",".","*","+","?","|","<",">","-","&","%");
    return Arrays.stream(input.split("")).map((c) -> {
                if (specialCharacters.contains(c)) return "\\" + c;
                else return c;
    }).collect(Collectors.joining());
}
Chancre answered 18/12, 2020 at 10:32 Comment(0)
L
0

The simple version ( without deprecated StringUtils.replaceAll ):

    String regex = "[\\[+\\]+:{}^~?\\\\/()><=\"!]";
    String query = "hello+Search}query";
    String replaceAll = query.replaceAll(regex, "\\\\$0");
Lev answered 17/11, 2022 at 10:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.