Java Regex在字符类中的非法转义字符 [英] Java Regex Illegal Escape Character in Character Class
问题描述
我正在尝试确定传递给我的Expressions类的表达式是否有运算符。 + - * / ^
分别用于加,减,乘,除和指数。
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.
感谢您的帮助。
推荐答案
不要逃避不需要转义的内容:
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()
)
这篇关于Java Regex在字符类中的非法转义字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!