我想从字符串中获取一个数字 -
if (list.get(k).contains("Total Weight: "))
{
//get the number between "Total Weight: " and "tonnes" and make it a float
}
字符串看起来像这样
Carriage ID Number: 1
Carriage type: Passenger Carriage
Tare Weight: 5.0
Total Weight: 9.725 tonnes
Number of passengers: 45
或
Carriage ID Number: 2
Carriage type: Goods Carriage
Tare Weight: 3.0
Total Weight: 8.0 tonnes
Goods Weight: 5.0 tonnes
Goods Description: Lego
答案 0 :(得分:1)
使用空格字符拆分字符串,将第3个字符串转换为浮点数:
String s = "Total Weight: 9.725 tonnes";
float tonnes = Float.parseFloat(s.split(" ")[2]);
答案 1 :(得分:0)
试试这个正则表达式:
import java.util.regex.Pattern;
String test = (Total Weight\:)\s*([0-9]*[\.]*[0-9]*)\s*(tonnes);
Pattern pattern = Pattern.compile (test);
Matcher result = pattern.matcher (yourInput);
If result.find () yourAnswer = result.group (2);