我正在嘗試設計一種可以決議字串形式的運算式的演算法。我希望能夠從給定的運算式中提取運算元和操作。另外,我希望演算法能夠識別括號平衡。不需要操作的優先級,因為如果有超過 1 個二進制操作,演算法的輸入將包含括號。對于一元運算,如果括號前出現“-”,則表示相應括號內的整個運算式為運算元。例子:
-parsing "a b" gives "a" and "b" as operands and " " as operation.
-parsing "(a/b) - (c*v)" gives "a/b" and "c*v" as operands and "-" as operation.
-parsing "((a/(b))) - (((c)*v))" gives the same result as above
-parsing "-a" gives operand as "a" and operation as "-"
-parsing "a (-c/v)" gives "a" and "-c/v" as operands and " " as operation
-parsing "-(c)" gives "c" is operand and "-" as operands
-parsing "(-(c))" gives same result as above
謝謝
uj5u.com熱心網友回復:
嘗試這個。
record Node(String name, Node left, Node right) {
@Override
public String toString() {
return "Node[" name
(left != null ? ", " left : "")
(right != null ? ", " right : "") "]";
}
}
和
static Node parse(String input) {
return new Object() {
int index = 0;
int ch() { return index < input.length() ? input.charAt(index) : -1; }
boolean eat(char expected) {
while (Character.isWhitespace(ch())) index;
if (ch() == expected) {
index;
return true;
}
return false;
}
Node factor() {
Node node;
boolean minus = eat('-');
if (eat('(')) {
node = expression();
if (!eat(')'))
throw new RuntimeException("')' expected");
} else if (Character.isAlphabetic(ch())) {
node = new Node(Character.toString(ch()), null, null);
index;
} else
throw new RuntimeException("unknown char '" (char)ch() "'");
if (minus) node = new Node("-", node, null);
return node;
}
Node expression() {
Node node = factor();
while (true)
if (eat('*')) node = new Node("*", node, factor());
else if (eat('/')) node = new Node("/", node, factor());
else if (eat(' ')) node = new Node(" ", node, factor());
else if (eat('-')) node = new Node("-", node, factor());
else break;
return node;
}
}.expression();
}
測驗:
static void testParse(String input) {
System.out.printf("%-22s -> %s%n", input, parse(input));
}
public static void main(String[] args) {
testParse("a b");
testParse("(a/b) - (c*v)");
testParse("((a/(b))) - (((c)*v))");
testParse("-a");
testParse("-a (-c/v)");
testParse("-(c)");
testParse("(-(c))");
}
輸出:
a b -> Node[ , Node[a], Node[b]]
(a/b) - (c*v) -> Node[-, Node[/, Node[a], Node[b]], Node[*, Node[c], Node[v]]]
((a/(b))) - (((c)*v)) -> Node[-, Node[/, Node[a], Node[b]], Node[*, Node[c], Node[v]]]
-a -> Node[-, Node[a]]
-a (-c/v) -> Node[ , Node[-, Node[a]], Node[/, Node[-, Node[c]], Node[v]]]
-(c) -> Node[-, Node[c]]
(-(c)) -> Node[-, Node[c]]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/534008.html
標籤:爪哇解析表达
上一篇:React決議localStorage問題(Uncaught(inpromise)SyntaxError:Unexpectedtoken'u',"functionst&q
