Reputation: 2184
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.
Upvotes: 3
Views: 21863
Reputation: 91
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");
Upvotes: 0
Reputation: 21995
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();
Upvotes: 6
Reputation: 29670
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
.
Upvotes: 0
Reputation: 15690
There's an app for that: Pattern.quote()
It escapes anything that would be recognized as regex pattern language.
Upvotes: 1