繁体   English   中英

如何用Java解析字符串?

[英]How to parse string with Java?

我正在尝试制作一个简单的计算器应用程序,该应用程序将采用这样的字符串

5 + 4 + 3 - 2 - 10 + 15

我需要Java将此字符串解析为数组

{5, +4, +3, -2, -10, +15}

假设用户可以在每个数字和每个运算符之间输入0或多个空格

我是Java的新手,所以我不确定如何完成此工作。

您可以使用Integer.parseInt来获取值,分割可以使用String类实现的字符串。 正则表达式可以工作,但我不知道该怎么做:3

看一下String.split()

String str = "1 + 2";
System.out.println(java.util.Arrays.toString(str.split(" ")));

[1,+,2]

请注意,split使用正则表达式,因此您必须用双引号将字符分隔。 或具有特殊含义的类似字符。 同样,一行中的多个空格将在解析数组中创建您需要跳过的空字符串。

这解决了简单的示例。 为了更严格地解析真实表达式,您需要创建一个语法并使用诸如Antlr之类的东西。

str为行缓冲区。

将Regex.match用于模式([-+]?[ \\t]*[0-9]+)

将所有匹配项累积到String[] tokens

然后,对于每个tokentokens

String s[] = tokens[i].split(" +");
if (s.length > 1)
    tokens[i] = s[0] + s[1];
else
    tokens[i] = s[0];

您可以使用正向后面:

    String s = "5  +  4  +  3   -   2 - 10 + 15";
    Pattern p = Pattern.compile("(?<=[0-9]) +");
    String[] result = p.split(s);

    for(String ss : result)
        System.out.println(ss.replaceAll(" ", ""));
    String cal = "5 + 4 + 3 - 2 - 10 + 15";
    //matches combinations of '+' or '-', whitespace, number
    Pattern pat = Pattern.compile("[-+]{1}\\s*\\d+");
    Matcher mat = pat.matcher(cal);
    List<String> ops = new ArrayList<String>();
    while(mat.find())
    {
        ops.add(mat.group());
    }
    //gets first number and puts in beginning of List
    ops.add(0, cal.substring(0, cal.indexOf(" ")));

    for(int i = 0; i < ops.size(); i++)
    {
        //remove whitespace
        ops.set(i, ops.get(i).replaceAll("\\s*", ""));
    }

    System.out.println(Arrays.toString(ops.toArray()));
    //[5, +4, +3, -2, -10, +15]

根据一些答案的输入,我发现这是最好的解决方案

// input
String s = "5 + 4 + 3 - 2 - 10 + 15";
ArrayList<Integer> numbers = new ArrayList<Integer>();

// remove whitespace
s = s.replaceAll("\\s+", "");

// parse string
Pattern pattern = Pattern.compile("[-]?\\d+");
Matcher matcher = pattern.matcher(s);

// add numbers to array
while (matcher.find()) {
  numbers.add(Integer.parseInt(matcher.group()));
}

// numbers
// {5, 4, 3, -2, -10, 15}

暂无
暂无

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

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