简体   繁体   中英

How to parse string with Java?

I am trying to make a simple calculator application that would take a string like this

5 + 4 + 3 - 2 - 10 + 15

I need Java to parse this string into an array

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

Assume the user may enter 0 or more spaces between each number and each operator

I'm new to Java so I'm not entirely sure how to accomplish this.

You can use Integer.parseInt to get the values, splitting the string you can achieve with String class. A regex could work, but I dont know how to do those :3

Take a look at String.split() :

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

[1, +, 2]

Note that split uses regular expressions, so you would have to quote the character to split by "." or similar characters with special meanings. Also, multiple spaces in a row will create empty strings in the parse array which you would need to skip.

This solves the simple example. For more rigorous parsing of true expressions you would want to create a grammar and use something like Antlr .

Let str be your line buffer.

Use Regex.match for pattern ([-+]?[ \\t]*[0-9]+) .

Accumulate all matches into String[] tokens .

Then, for each token in tokens :

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

You can use positive lookbehind:

    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]

Based off the input of some of the answers here, I found this to be the best solution

// 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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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