且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java Regex在字符类中的非法转义字符

更新时间:2022-06-10 22:44:17

不要逃避不需要转义的内容:

Don't escape what needs not to be escaped:

return expression.matches("[-+*/^]+");

应该可以正常工作。大多数正则表达式元字符( + * 等)在字符类中使用时会失去特殊含义。你需要注意的是 [ - ^ ] 。而对于最后三个,你可以策略性地在其中放置char类,因此它们不具有其特殊含义:

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:


  • ^ 可以放在开头括号之后的任何地方: [a ^]

  • - 可以放在开始括号之后或者在结束括号之前: [ - a] [a - ]

  • ] 可以放在左括号后面: [] a]

  • ^ 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






另一个注意事项: String.matches()会尝试将整个字符串与模式匹配,所以除非你的字符串只包含一堆运算符,你需要使用像 .matches(。* [ - + * / ^]。*); 这样的东西(或使用 匹配器。 find()


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