Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Regex Illegal Escape Character in Character Class

Tags:

java

regex

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 had the special characters escaped properly but I keep getting the error: "illegal escape character" when trying to compile.

Thanks for your help.

like image 316
Anthony Jack Avatar asked Sep 30 '11 00:09

Anthony Jack


1 Answers

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

like image 159
NullUserException Avatar answered Oct 07 '22 04:10

NullUserException