How to escape certain characters in java

∥☆過路亽.° 提交于 2019-12-01 08:49:54

Would this work?

StringBuilder sb = new StringBuilder();
for (char c : myString.toCharArray())
{
    switch(c)
    {
        case '[':
        case ']':
        case '.':
        case '^':
        case '+':
        case '\\':
            sb.append('\\');
            // intended fall-through
        default:
            sb.append(c);
    }
}
String escaped = sb.toString();

There's an app for that: Pattern.quote()

It escapes anything that would be recognized as regex pattern language.

To escape a String to be used as a literal in a regular expression you can use Pattern.quote()

or just surround the string with \\Q and \\E.

Dharminder

The \Q and \E and java.util.Pattern.quote() are the same approach.

However, this approach only works for a subset of regex flavors.

Check out the following link and you'll see that 4 of 15 flavors support it. So you're better off using Grodriguez's approach if you need to execute your regex in anything other than Java, such as javascript (which uses ECMA).

http://www.regular-expressions.info/refflavors.html

Here is a one-liner that might work.

"text to escape".replaceAll("([\\\\\\[\\]\\.\\^\\+])","\\\\$1");

You do this by prepending \ to the character you want to escape.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!