0

How to check if String contains only operators?

code:

 public void convertString(String s){
    String[] arr = s.split("");


    for (int i = 0; i < arr.length ; i++) {
        stringStack.push(arr[i]);
    }
    
     if (stringStack.peek().matches("[0-9]+")){
         digitStack.push(Double.valueOf(stringStack.pop()));
     }else if (stringStack.peek().matches("[(+=-*/^)]+")){

     }

     System.out.println(digitStack);

}

in this line "[(+=-*/^)]+" a receive error:

Illegal character range (to < from)

How to check if String contains only operators?

Dartweiler
  • 85
  • 8

2 Answers2

1

- in [ ] has a special meaning, e.g. [0-9].

Add an escape character, and it should work. [(+=\-*/^)]+

MC Emperor
  • 22,334
  • 15
  • 80
  • 130
Zen
  • 621
  • 4
  • 11
0

You have actually two options:

  1. Escape the dash with a backslash (\- instead of -). That'll instruct the regex engine to parse the dash as a literal dash, instead of a range divider. This is what Zen already mentioned.

  2. The second option is to put the dash at the beginning or at the end of the character class. If the dash is place in either, then the regex engine knows that the dash is not part of a character range.

    [(+=*/^)-]
    
MC Emperor
  • 22,334
  • 15
  • 80
  • 130