Java infix string tokenization

I am implementing the Shunting Yard Algorithm in Java as a side project for my AP Computer Science class. I implemented simple in Javascript, only with basic arithmetic expressions (addition, subtraction, multiplication, division, exponentiation). To break this down into an array, I searched for each of the ( +-*/^) operators , as well as numbers and parentheses, and I put a space around them and then split it into an array. For example, the infix line 4+(3+2)will be made into 4 + ( 3 + 2 ), and then split into spaces.

However, I feel that this method is very slow, and it becomes more complex and ineffective for implementation when you start adding mathematical functions such as sine, cosine, tangent, absolute value and others.

What would be the best way to split a type string sin(4+3)-8into an array ["sin","(" 4,"+",3,")","-",8]?

I could use regex for this, but I don't understand them very well, and I'm trying to study them, so if this were the best solution for them, could he explain what he was doing?

+4
source share
1 answer

Try .spliting for regex

(?<=[^\.a-zA-Z\d])|(?=[^\.a-zA-Z\d])

, , -- .

  • (?<=[^\.a-zA-Z\d]) - lookbehind. , - , (?<=...).
    • [^\.a-zA-Z\d] . , [^...].
      • \. ..
      • a-z a z.
      • a-z , .
      • \d [0-9], .
  • | "" . .
  • (?=[^\.a-zA-Z\d]) , , . , , (?=...).

java :

String str = "sin(4+3)-8";
String[] parts = str.split("(?<=[^\\.a-zA-Z\\d])|(?=[^\\.a-zA-Z\\d])");

:

["sin","(" 4,"+",3,")","-","8"]
+3

Source: https://habr.com/ru/post/1524086/


All Articles