java java正则表达式,匹配数学运算符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15034693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java regex, matching math operators
提问by Ted
I am trying to write a regex to match math operators to a char. I've tried a bunch of different things but i keep getting:
我正在尝试编写一个正则表达式来将数学运算符与字符匹配。我尝试了很多不同的东西,但我不断得到:
Syntax error on tokens, Expression expected instead
令牌上的语法错误,应改为表达
my code looks like this:
我的代码是这样的:
public static void readMath(char c) {
if(c == [+\-*/]) {
// do some stuff
}
}
i've tried escaping different things etc etc. i can't seem to get it to work.
我试过逃避不同的事情等等。我似乎无法让它工作。
采纳答案by rgettman
You shouldn't need a regular expression to match a single char
. That's not how you use regular expression in Java anyway.
您不应该需要正则表达式来匹配单个char
. 无论如何,这不是您在 Java 中使用正则表达式的方式。
if(c == '+' || c == '-' || c == '/' || c == '*') {
// do some stuff
}
Or you could try a switch statement instead.
或者您可以尝试使用 switch 语句。
switch (c)
{
case '+':
case '-':
case '*':
case '/':
// do some stuff
break;
}
回答by MikeM
public static void readMath( char c ) {
if ( String.valueOf( c ).matches( "[-+*/]" ) ) {
// do stuff
}
}
回答by hthserhs
You can do the following.
您可以执行以下操作。
Initialize a list of allowed operators in the class like this:
像这样初始化类中允许的运算符列表:
private static List<Character> ops = new ArrayList<Character>();
static {
ops.add('+');
ops.add('-');
ops.add('*');
ops.add('/');
}
And to check if a char
c
is one of the above operators use:
并检查 achar
c
是否是上述运算符之一,请使用:
if(ops.contains(c)) {
}
回答by PermGenError
You don't really need regex, use either Enum or switch. here is an Enum example:
你真的不需要正则表达式,使用 Enum 或 switch。这是一个枚举示例:
public enum Operation {
PLUS('+'),
MINUS('-'),
TIMES('*'),
DIVIDE('/')
private final char symbol;
Operation(char symbol) { this.symbol = symbol; }
public char toChar() { return symbol; }
}
public void checkOp(){
if(Operation.PLUS.toChar()=='+') {
}
}