Java Regex Illegal Escape Character in Character Class

后端 未结 1 1988
既然无缘
既然无缘 2020-12-01 23:44

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 ex

相关标签:
1条回答
  • 2020-12-02 00:15

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

    0 讨论(0)
提交回复
热议问题