0

Lets say i have this expression I10I20I-3++ which should give me 27. I just can't seem to find a way of removing those I's, or if it is any other letter from the string. In addition I have to figure out a way to then evaluate the expression. I tried using regex, but no luck:

public static String removeIs(String input)
{
    //String check = input.replaceAll("[^/+/-/*//^0-9/-]+", " ");
    String check = input.replaceAll("[^-+*/^0-9/-](?![^(]*\\))"," ");
    return check;
}
Perception
  • 79,279
  • 19
  • 185
  • 195
  • i think you should check `how to evaluate infix Expression in java` Link :http://stackoverflow.com/questions/7185589/how-to-calculate-expression-in-java – Arpit Feb 23 '13 at 09:50
  • 1
    What's that `I10I20I-3++`? Is it just a test string? What do you mean by ,,should give me 27''? – Wookie88 Feb 23 '13 at 09:54
  • @Wookie88 - its a calculator expression, where the operands are separated by `I`, and the operators all come at the end. – Perception Feb 23 '13 at 09:58
  • Thats a postfix expression with the letter I to divide the numbers, i need to be able to have negative numbers in my postfix expression. 27 is the result when you evaluate the expression without the I's –  Feb 23 '13 at 16:50

1 Answers1

1

The expression for finding any non-operator non-digit character is:

[^0-9+\-\*\/]

You've said in the comment below the Q that you're writing calculator. Please note that you have unknown number of digits and operators in your string, so it would probably be better to make a loop and iterate through string and manually grab digits and operators for using in your calculator and NOT by using regex backreferences. Btw: why are you replacing I with spaces? does it make any difference for you what is the separator in string?

I've created quite an advanced regex-based JS code parser quite a while ago and from this experience I can tell that creating one, monstrous expression for parsing everything at once is usually bad idea.

Wookie88
  • 33,079
  • 4
  • 27
  • 32