Java Regex Illegal Escape Character in Character Class
I'm trying to determine whether or not a expression passed into my Expressions class has an operator. Either +-*/^
for add, subtract, multiply, divide, and exponent respectively.
What is wrong with this code?
private static boolean hasOperator(String expression)
{
return expression.matches("[\+-\*/\^]+");
}
I thought that I h开发者_StackOverflowad the special characters escaped properly but I keep getting the error: "illegal escape character" when trying to compile.
Thanks for your help.
Don't escape what needs not to be escaped:
return expression.matches("[-+*/^]+");
should work just fine. Most regex metacharacters (.
, (
, )
, +
, *
, etc.) lose their special meaning when used in a character class. The ones you need to pay attention to are [
, -
, ^
, and ]
. And for the last three, you can strategically place in them char class so they don't take their special meaning:
^
can be placed anywhere except right after the opening bracket:[a^]
-
can be placed right after the opening bracket or right before the closing bracket:[-a]
or[a-]
]
can be placed right after the opening bracket:[]a]
But for future reference, if you need to include a backslash as an escape character in a regex string, you'll need to escape it twice, eg:
"\\(.*?\\)" // match something inside parentheses
So to match a literal backslash, you'd need four of them:
"hello\\\\world" // this regex matches hello\world
Another note: String.matches()
will try to match the entire string against the pattern, so unless your string consists of just a bunch of operators, you'll need to use use something like .matches(".*[-+*/^].*");
instead (or use Matcher.find()
)
精彩评论