Java regex, соответствующие переменные в математическом выражении [закрыто]JAVA

Программисты JAVA общаются здесь
Anonymous
Java regex, соответствующие переменные в математическом выражении [закрыто]

Сообщение Anonymous »

У меня есть ввод строки, который представляет формулу, подобную: < /p>

BMI = ( Weight / ( Height * Height ) ) * 703


I want to be able to extract all legal variables into a String[]

Legal variables are determined with almost the same rules as Java variable naming convention, except only alphanumeric characters are allowed:


Any alphabet character upper or lower, Может сопровождаться цифрой < /li>
Любое слово /текст < /li>
Любое слово /текст, за которым следует цифра < /li>
< /ul>

Поэтому я ожидаю, что вывод будет выглядеть так: < /p>

BMI
Weight
Height
< /code>

Это моя текущая попытка: < /strong> < /p>

/* 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 variablesArray (String expression)
{
List varList = null;
StringBuilder sb = null;
if (expression!=null)
{
sb = new StringBuilder();

//list that will contain encountered words,numbers, and white space
varList = new ArrayList();

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

Результат не так, как я ожидал. У меня есть дополнительные пустые линии, дважды я получил «высота», и не должен был получить число: < /p>

BMI

Weight

Height

Height

703


Подробнее здесь: https://stackoverflow.com/questions/111 ... expression

Вернуться в «JAVA»