简体   繁体   English

Java正则表达式匹配数学表达式模式

[英]Java regex matching the mathematical expression pattern

I'm trying to match a string pattern like this recursively or iteratively. 我试图递归或迭代地匹配这样的字符串模式。

term :- can be any variable(string) or integer 术语:-可以是任何变量(字符串)或整数
expression :- term + expression or term * expression or term / expression or term - expression 表达式:-术语+表达式或术语*表达式或术语/表达式或术语-表达式

The idea is to find a matching pattern for mathematical expression like this 这样的想法是为这样的数学表达式找到匹配的模式

ZING^30*sin(45)+46*LENGTH-20 ZING ^ 30 * sin(45)+ 46 * LENGTH-20

Let's assume that the term is ready. 我们假设该术语已经准备好。

As usual, I'll start from a very bad one... in java. 和往常一样,我将从Java中的一个非常糟糕的问题开始。

[[term\\+]*[term\\*]*[term\\\]*[term\\-]*]+term

You're using the wrong tool for the job. 您为该工作使用了错误的工具。 Regular expressions can't describe grammars with recursive syntaxes, by definition. 根据定义,正则表达式无法使用递归语法来描述语法。 Look up the Chomsky Hierarchy. 查找Chomsky层次结构。 You need an expression parser. 您需要一个表达式解析器。 Look up the Dijkstra Shunting-yard algorithm, or 'recursive descent expression parser'. 查找Dijkstra Shunting-yard算法或“递归下降表达式解析器”。

This looks like homework, so I'm not going to give you a complete answer. 这看起来像作业,所以我不会给您完整的答案。 If you know how to use moderately complex regexes, you should be able to come up with a regex to represent your "term"--it shouldn't be too difficult. 如果您知道如何使用中等复杂的正则表达式,那么您应该能够提出一个正则表达式来代表您的“术语”,这应该不太困难。 Now the regex for "expression" will be a term, followed by zero or more occurrences of "operator followed by term" (operator is one of + , - , * , / , maybe ^ ?). 现在,用于“表达式”的正则表达式将是一个术语,后面是零个或多个出现的“运算符后跟术语”(运算符是+-*/ ,也许是^ ?之一)。 That is, expression will be "term", or "term op term", or "term op term op term", etc. 也就是说,表达式将是“ term”或“ term op term”或“ term op term op term”等。

Note: this is how you'd write a regex that tells you whether the input has the correct format, but it won't help you break it down into parts. 注意:这是您编写正则表达式的方式,该正则表达式告诉您输入是否具有正确的格式,但这不会帮助您将其分解为多个部分。 For that, you'd need a different regex (or two) that you would match in a loop. 为此,您需要在循环中匹配的另一个正则表达式(或两个)。 I can't tell just what your requirements are, though. 不过,我不能说出您的要求是什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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