我有一个包含以下多行的字符串:
current num = 13.2
第一部分current num =
始终相同,但后面的数字会有所不同。如何查看整个字符串并将数值放入数组?
答案 0 :(得分: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());
}
}