简体   繁体   English

正则表达式提取方程中的数学变量

[英]Regex to extract mathematical variables in equation

I have a mathematical expression given as a String and I have to extract all the variables which are identified as a letter, possibly followed by a number (eg x or x0 ).我有一个作为String给出的数学表达式,我必须提取所有标识为字母的变量,可能后跟一个数字(例如xx0 )。 It works for simple expressions but if I try it with a more complicated equation I pick also numbers which I don't want since my goal is to determinate if the two equations use the same variables.它适用于简单的表达式,但如果我尝试使用更复杂的方程,我也会选择我不想要的数字,因为我的目标是确定两个方程是否使用相同的变量。

     String expression = "((x0+(2.0^x))/(21.1-x0))";
     for (String variable : expression.split("[^a-z0-9?]")) {
       if(!variable.isEmpty()){
         System.out.print(variable + " ");
     };

and the output is: output 是:

x0 2 0 x 21 1 x0

where I wanted我想要的地方

x0 x x0

why it takes also digits without a letter before?为什么它之前也需要没有字母的数字? I already tried every possible combination of \\b and I didn't find anything online.我已经尝试了\\b的所有可能组合,但我没有在网上找到任何东西。

Instead of splitting on what you don't want, you can also match what you are looking for.您也可以匹配您正在寻找的内容,而不是拆分您不想要的内容。

\b[a-z]\d*\b

Regex demo |正则表达式演示| Java demo Java演示

String regex = "\\b[a-z]\\d*\\b";
String s = "((x0+(2.0^x))/(21.1-x0))";
List<String> matches = new ArrayList<String>();
Matcher m = Pattern.compile(regex, Pattern.CASE_INSENSITIVE).matcher(s);

while (m.find()) {
    matches.add(m.group());
}

for (String match : matches) {
    System.out.println(match);
}

Output Output

x0
x
x0

The expression keeps the digits because they are not included in the regex search for the split method when creating the String variable .表达式保留数字,因为在创建String variable时,它们不包含在split方法的正则表达式搜索中。

Try splitting at one or many non-alphanumeric characters ( \W+ ), which may be followed by zero or many digits ( \d* ).尝试拆分一个或多个非字母数字字符 ( \W+ ),其后可能跟零个或多个数字 ( \d* )。

"\W+\d*"

Adding \d* to the end of your existing regex should also work.\d*添加到现有正则表达式的末尾也应该有效。

"[^a-z0-9?]\d*"

Tested on regex101 with Java 8.使用 Java 8 在regex101上测试。

Please let me know whether this resolved your question.请让我知道这是否解决了您的问题。

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

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