Escape any non-alphanumeric characters in a string using Regex

Viewed 177

I would like to escape non-alphanumeric characters occurring in a string as follows:

Say, the original string is: "test_", I would like to transform as "test\_".

In order to do this, one approach I can take by scanning the original string, and constructing a new string and while a non-alphanumeric character is found, append a '\' in front of this character.

But I am wondering if there is any cleaner approach to do the same using regular expression.

1 Answers

You can use the replaceable parameter as shown below:

public class Main {
    public static void main(String[] args) {
        String s = "test_";
        s = s.replaceAll("[^\\p{Alnum}]", "\\\\$0");

        System.out.println(s);
    }
}

Output:

test\_

Notes:

  1. $0 represents the string matched by the complete regex pattern, [^\\p{Alnum}].
  2. \p{Alnum} specifies alphanumeric character and ^ inside [] is used to negate the pattern. Learn more about patterns from the documentation.
  3. Notice the extra pair of \\ which is to escape \ that has been used to escape \.
Related