简体   繁体   English

如何仅从字符串方程式Java中提取字母

[英]How to extract only the letters from string equation Java

I'm trying to extract the letters for the variables in a String "equation". 我正在尝试提取字符串“ equation”中变量的字母。 Then save it to a String array called variables. 然后将其保存到一个名为变量的String数组中。 However, when I print the variables array it is full of "empty containers" 但是,当我打印变量数组时,它充满了“空容器”

How do I make it so that there are no empty spaces in the String[] variables containers? 如何使String []变量容器中没有空格?

String equation = "(a+2)/3*b-(28-c)";

String[] variables = equation.split("[+-/*0-9()]");

for(int i = 0 ; i < variables.length; ++i)
{
    System.out.println(variables[i]);
}

Given that your equation may have nested content, a single regex solution may not be optimal. 鉴于您的方程式可能包含嵌套的内容,因此单个正则表达式解决方案可能不是最佳选择。 Instead, I recommend using a pattern matcher, and just scanning the entire equation for letter variables: 相反,我建议使用模式匹配器,并只扫描整个方程以查找字母变量:

String equation = "(a+2)/3*b-(28-c)";
String pattern = "[A-Za-z]+";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(equation);

while (m.find()) {
     System.out.println("Found a variable: " + m.group(0));
}

Found a variable: a
Found a variable: b
Found a variable: c

Note: This solution assumes you only want the variable names themselves, and you don't care about things like prefixes or coefficients. 注意:此解决方案假定您希望变量名本身,并且不关心前缀或系数之类的内容。

First replace all non-variable characters( matched by [+*-\\\\/0-9)(] ) with empty string then change it to char array, try this one 首先用空字符串替换所有非可变字符(由[+*-\\\\/0-9)(]匹配),然后将其更改为char数组,尝试这个

String equation="(a+2)/3*b-(28-c)";
char[] variables= equation.replaceAll("[+*-\\/0-9)(]","").toCharArray();        

  for(int i = 0 ; i < variables.length; ++i)
{
    System.out.println(variables[i]);
}

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

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