简体   繁体   中英

java regex, matching math operators

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.

public static void readMath( char c ) {
    if ( String.valueOf( c ).matches( "[-+*/]" ) ) {
        // do stuff
    }
}

You shouldn't need a regular expression to match a single char . That's not how you use regular expression in Java anyway.

if(c == '+' || c == '-' || c == '/' || c == '*') {
      // do some stuff
}

Or you could try a switch statement instead.

switch (c)
{
case '+':
case '-':
case '*':
case '/':
     // do some stuff
     break;
}

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:

if(ops.contains(c)) {

}

You don't really need regex, use either Enum or switch. here is an Enum example:

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()=='+') {

}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM