我正在构建一个可以解决公式的计算器,作为我的一个项目,在该项目中我遇到了诸如 2x+7 这样的字符串将被标记为“2x”、“+”、“7”的问题。
我需要将其正确拆分为常量和变量,这意味着 2x 应该是 "2"、 "x"。我该如何做到这一点而不影响包括 Sin 和 Cos 函数等在内的复杂公式?
例如,我希望 16x + cos(y) 被标记为 "16"、 "x"、 "+"、 "cos"、 "("、 "y"、 ")"
最佳答案
This problem would be pretty complicated, and this answer is just an example.
也许,我们想弄清楚我们可能有什么类型的方程,然后我们会开始设计一些表达式。例如,我们可以看一下:
([a-z]+)|([-]?\d+)|[-+*\/]
Demo 1
或者:
([a-z]+)|([-]?\d+)|([-+*\/])|(\(|\))
Demo 2
示例
import java.util.regex.Matcher;
import java.util.regex.Pattern;
final String regex = "([a-z]+)|([-]?\\d+)|([-+*\\/])";
final String string = "2x+7\n"
+ "2sin(2x + 2y) = 2sin(x)*cos(2y) + 2cos 2x * 2sin 2y\n"
+ "2sin(2x - 2y) = -2tan 2x / cot -2y + -2cos -2x / 2sin 2y\n";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
正则表达式电路
jex.im可视化正则表达式:
对于如何最好地构建此问题的解决方案,我真的没有任何建议。但是,也许您想首先对方程进行分类,然后设计一些类/方法来处理每个感兴趣的类别,并且在需要正则表达式的情况下,您可以为您希望实现的所需目的设计一个/多个表达式。
关于java - 如何从字符串分词器函数中设计和分割标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56822490/