How to Escape Special, Meta Characters with Backslashes in Java


How can we add an escape character (i.e. the backslash \) in front of all special characters in a string?

Suppose we want to replace all special characters in the following to string.

String str = "{key:2}";

The resulting string might look something like this:

String escaped = "\\{key:2\\}";

The resulting string contains a double backslash because the backslash itself needs to be escaped as well.

1. Escape a single character

If we know exactly which characters to escape, we can call replace() on our string using the String API.

String escaped = str.replace("}", "\\}")
                    .replace("{", "\\{");

2. Escape all meta characters using for loop

Suppose we have an array of all the special, meta characters.

String[] specialChars = {
  "\\","^","$","{","}","[","]","(",")",
  ".","*","+","?","|","<",">","-","&","%"
};

We can escape all these characters by simply looping through them and prepending a double backslash to each character.

private String escape(String str) {
  for (String s : specialChars) {
    if (str.contains(s)) {
      str = str.replace(s, "\\" + s);
    }
  }
  return str;
}

3. Escape all meta characters using Stream API

We can obtain the same result using the Stream API as well.

Maybe this time, we’re starting with a list of special characters.

List<String> specialChars = Arrays.asList(
  "\\","^","$","{","}","[","]","(",")",
  ".","*","+","?","|","<",">","-","&","%"
);

Then, we can use the contains() method on the list to check each character in the string.

private String escape(String str) {
  return Arrays
    .stream(str.split(""))
    .map(c -> {
      if (specialChars.contains(c)) {
        return "\\" + c;
      } else {
        return c;
      }
    })
    .collect(Collectors.joining());
}