Java Regex Illegal Escape Character in Character Class

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

Leave a Comment