从数学方程中提取变量

时间:2016-04-10 04:15:05

标签: java regex pattern-matching

我有一个像

这样的字符串
  

a +(b * 6)< = cat * 45&& cat = dog

我正在尝试提取变量a, b, cat, dog。以下是我的代码。

        Set<String> varList = null; 
        StringBuilder sb = null; 
        String expression = "a+(b * 6) <= cat*45 && cat = dog";
        if (expression!=null)
        {
            sb = new StringBuilder(); 

            //list that will contain encountered words,numbers, and white space
            varList = new HashSet<String>();

            Pattern p = Pattern.compile("[A-Za-z\\s]");
            Matcher m = p.matcher(expression);

            //while matches are found 
            while (m.find())
            {
                //add words/variables found in the expression 
                sb.append(m.group());
            }//end while 

            //split the expression based on white space 
            String [] splitExpression = sb.toString().split("\\s");
            for (int i=0; i<splitExpression.length; i++)
            {
                varList.add(splitExpression[i]);
            }
        }

        Iterator iter = varList.iterator();
        while (iter.hasNext()) {
            System.out.println(iter.next());
        }

我得到的输出是:

ab
cat
dog

必需的输出:

a
b
cat
dog

这里的情况是,变量可能会或可能不会被空格分隔。当有空白时,输出是好的。但如果变量没有被空格分隔,我输出错误。有人可以建议我Pattern吗?

5 个答案:

答案 0 :(得分:3)

为什么要使用正则表达式 $txt = "<?php include 'work/uploads/".$php_id.".html';?>"; $slot = file_put_contents('../offer/slots.php', $txt.PHP_EOL , FILE_APPEND); fwrite($slot, $txt); fclose($slot); $theCounterFile = "../offer/count.txt"; $oc = file_put_contents($theCounterFile, file_get_contents($theCounterFile)+1); fwrite($oc); fclose($oc); 循环来提取单词,然后将它们全部连接成一个字符串,只是为了再次分割该字符串?

只需使用正则表达式中找到的单词。

嗯,就是说,从表达式中删除空格(Line 81 : fwrite() expects parameter 1 to be resource, integer given Line 82 : fclose() expects parameter 1 to be resource, integer given Line 85 : fwrite() expects at least 2 parameters, 1 given Line 86 : fclose() expects parameter 1 to be resource, integer given )并使其与整个单词(find())匹配,当然。

\\s

答案 1 :(得分:1)

如果你的变量只是字母串,你可以使用像这样的简单正则表达式来搜索它们。

正则表达式: [A-Za-z]+

Regex101 Demo

答案 2 :(得分:1)

此正则表达式应该有效(variable name can start with uppercase or lowercase and can then contain digit(s), underscore, uppercase and lowercase

\b[A-Za-z]\w*\b

<强> Regex Demo

Java代码

Set<String> set = new HashSet<String>();
String line = "a+(b * 6) <= cat*45 && cat = dog";
String pattern = "\\b([A-Za-z]\\w*)\\b";

Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);

while (m.find()) {
    set.add(m.group());
}
System.out.println(set);

<强> Ideone Demo

答案 3 :(得分:1)

我相信你应该用&#34; [A-Za-z] +&#34;替换你的正则表达式。 我只是用Python模拟它

>>> re.findall('[A-Za-z]+', 'a+(b * 6) <= cat*45 && cat = dog')
['a', 'b', 'cat', 'cat', 'dog']
>>>

接下来,将结果列表放入一个集合中:

>>> rs = set(re.findall('[A-Za-z]+', 'a+(b * 6) <= cat*45 && cat = dog'))
>>> for w in rs:
...     print w,
...
a b dog cat
>>>

答案 4 :(得分:0)

完全正常工作的代码

public static void main(String[] args) {
    Set<String> varList = null; 
    StringBuilder sb = null; 
    String expression = "a+(b * 6) <= cat*45 && cat = dog";
    if (expression!=null)
    {
        sb = new StringBuilder(); 

        //list that will contain encountered words,numbers, and white space
        varList = new HashSet<String>();

        Pattern p = Pattern.compile("[A-Za-z\\s]+");
        Matcher m = p.matcher(expression);

        //while matches are found 
        while (m.find())
        {
            //add words/variables found in the expression 
            sb.append(m.group());
            sb.append(",");
        }//end while 

        //split the expression based on white space 
        String [] splitExpression = sb.toString().split(",");
        for (int i=0; i<splitExpression.length; i++)
        {
            if(!splitExpression[i].isEmpty() && !splitExpression[i].equals(" "))
                varList.add(splitExpression[i].trim());
        }
    }

    Iterator iter = varList.iterator();
    while (iter.hasNext()) {
        System.out.println(iter.next());
    }
}