我有一个字符串输入,它代表一个公式,例如:
BMI = ( Weight / ( Height * Height ) ) * 703
我希望能够将所有合法变量提取到String[]
合法变量的确定规则与 Java 变量命名约定几乎相同,但只允许使用字母数字字符:
- 任何大写或小写字母字符都可以后跟一个数字
- 任何单词/文本
- 任何单词/文本后跟一个数字
因此,我希望输出如下所示:
BMI
Weight
Height
这是我目前的尝试:
/* helper method , find all variables in expression,
* Variables are defined a alphabetical characters a to z, or any word , variables cannot have numbers at the beginning
* using regex pattern "[A-Za-z0-9\\s]"
*/
public static List<String> variablesArray (String expression)
{
List<String> varList = null;
StringBuilder sb = null;
if (expression!=null)
{
sb = new StringBuilder();
//list that will contain encountered words,numbers, and white space
varList = new ArrayList<String>();
Pattern p = Pattern.compile("[A-Za-z0-9\\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]);
}
}
return varList;
}
结果并不如我所料。我得到了额外的空行,两次得到“高度”,不应该得到一个数字:
BMI
Weight
Height
Height
703