0

I have a string containing multiple lines of the following:

current num = 13.2

The first part, current num =, is always the same, however the number after varies. How can I go through the whole string and put the number values into an array?

Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331
user3307102
  • 305
  • 1
  • 4
  • 15
  • Where do you get the String from? Do you read it from a file with one of these statments per line, or something like that? – wastl May 23 '14 at 22:22
  • You can do this with regular expressions. Look at [this question](http://stackoverflow.com/questions/16817031/how-to-iterate-over-regex-expression). –  May 23 '14 at 22:23
  • @wastl the string is an html file. So its not one of the statements per line. They are dispersed all over the place. – user3307102 May 23 '14 at 22:26
  • Is the white space always the same? Do you know ahead of time how many values there will be? Is the data type always `int` or could there be other number formats (exponential, floating point). Can there be minus signs? Lots of things to worry about when parsing numbers... – Floris May 23 '14 at 22:28
  • possible duplicate of [Java. Find all numbers in the String. Need check](http://stackoverflow.com/questions/13440506/java-find-all-numbers-in-the-string-need-check) – Russia Must Remove Putin May 23 '14 at 23:10

1 Answers1

4
public static ArrayList<BigDecimal> getNumbers(String s) {
    ArrayList<BigDecimal> numbers = new ArrayList<>();

    // regular expression
    Pattern p = Pattern.compile("current num\\s?=\\s?(\\d+\\.?\\d*)");
    Matcher m = p.matcher(s);
    // find matches
    while (m.find()) {
        // print out the number after current num =
        numbers.add(new BigDecimal(m.group(1)));
    }
    return numbers;
}

public static void main(String[] args) {
    String s = "current num = 120 current num = 50.5";

    ArrayList<BigDecimal> numbers = getNumbers(s);
    for (BigDecimal number: numbers) {
        System.out.println(number.toString());
    }
}
user432
  • 3,506
  • 17
  • 24
  • Thanks this is working well. But I made a small adjustment to my question: the number is rounded to one decimal place. How would I get it to save that part too? – user3307102 May 23 '14 at 22:35
  • Sorry I think I worded that wrong. I meant to say that the original string contains decimal values. I do not need to round them, as they are already rounded to 1 decimal place. All I need is for the regex to include the decimal and the number after it. How can I do that? Thanks again. – user3307102 May 23 '14 at 22:56
  • @user3307102 Pretty sure we got it now. – user432 May 23 '14 at 23:02