How to parse string with Java?

18,925

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}
Share:
18,925
maček
Author by

maček

Updated on June 04, 2022

Comments

  • maček
    maček almost 2 years

    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.