问题
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