我想从我的字符串中获取整数值。下面是我的例子。
String strScore = "Your score is 10. Probability in the next 2 years is 40%";
但我只想得到10分。我该怎么做?
更新:
String firstNumber = strScore.replaceFirst(".*?(\\d+).*", "$1");
bfLog.createEntry( firstNumber );
我将其保存到 sqlite 数据库。
您可以使用其中一种String正则表达式replace方法来捕获捕获组中的第一个数字:
String firstNumber = strScore.replaceFirst(".*?(\\d+).*", "$1");
.*?消耗初始非数字(非贪婪)(\\d+)获取组中的一个或多个可用数字!.*其他一切(贪婪)。这取决于您的字符串中是否有任何其他内容可以更改。
如果除了数字之外它总是相同的,你可以使用
int score = Integer.parseInt(strScore.substring(14,16))
因为数字“10”位于字符串的索引 14 和 15。如果您的字符串中的其他内容发生了变化,您应该使用正则表达式:
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html
你可以试试这个:
String strScore = "Your score is 10. Probability in the next 2 years is 40%";
String intIndex = strScore.valueOf(10);
String intIndex = 10 // Result