我正在构建一个 Android 应用程序,在其中我只想从收件箱消息中提取数值(Rs.875)并将其全部添加。 我该怎么做,请给一些想法。
示例:消息将是这样的 - 1> 9055668800充值196卢比成功。使用免费应用程序立即为预付费手机充值。 2>您好,我们已收到 2000.00 卢比的付款,编号为 NF789465132。请继续关注我们确认您的预订。
我只需计算文本中的金额。
最佳答案
你可以这样做:你可以使用 Regex
喜欢 "(?<=Rs.)\\d+[\\.\\d]*"
仅获取问题中所要求的金额。 我只需计算文本中的金额。
String message = "Recharge of Rs.196 for 9055668800 is successful. Recharge prepaid mobile instantly using freecharge app. hi, we have received payment of Rs.2000.00 with ref.no.NF789465132. Stay tuned while we confirm your booking.";
Pattern pattern = Pattern.compile("(?<=Rs.)\\d+[\\.\\d]*");
Matcher matcher = pattern.matcher(message);
double sum = 0;
while (matcher.find()) {
String digit = matcher.group();
System.out.println("digit = " + digit);
sum += Double.parseDouble(digit);
}
System.out.println("sum = " + sum);
这是输出:
digit = 196
digit = 2000.00
sum = 2196.0
关于java - 如何从字符串中提取数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35667221/