How to escape certain characters in java

喜欢而已 提交于 2019-12-01 06:43:36

问题


I need to escape characters like ^, ., [, ], + and \ (tabs and newlines won't be an issue), while leaving others like * and ?.

EDIT = More specifically, I have a string with these characters, and I need to escape them so that they are not matched by regular expressions. I need to prepend \ to each of these characters, but doing so individually would take 7 or 8 scans and I'd like to do it within just one pass (IE: anything that matches is prepended with \)

How do I do this?

Thanks.


回答1:


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();



回答2:


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

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




回答3:


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.




回答4:


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");



回答5:


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



来源:https://stackoverflow.com/questions/7772317/how-to-escape-certain-characters-in-java

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