Im building an android application in which i want to extract only the numeric values(Rs.875) from the inbox message and add them all. how can i do it please give some ideas.
example:The messages will be like this- 1> Recharge of Rs.196 for 9055668800 is successful. Recharge prepaid mobile instantly using freecharge app. 2>hi, we have received payment of Rs.2000.00 with ref.no.NF789465132. Stay tuned while we confirm your booking.
I have to calculate only the amount in from the text.
You can do it like this: You can use Regex
like "(?<=Rs.)\\\\d+[\\\\.\\\\d]*"
to get only the amount as asked in the question. I have to calculate only the amount in from the text.
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);
And it is the out put:
digit = 196
digit = 2000.00
sum = 2196.0
Here's one without regex:
String[] messageParts = message.split(" ");
double sum = 0;
for (String messagePart : messageParts) {
if (messagePart.startsWith("Rs.")) {
sum += Double.parseDouble(messagePart.substring(messagePart.indexOf("Rs.") + 3));
}
}
System.out.println("Sum: " + sum);
And the output is
Sum: 2196.0
If you want to extract only the recharge amount from the given String then you can use a Regex like Rs.[0-9.]+
. You can then parse it to Integer or Double to sum it up.
Here is a quick code snippet:
public static void main (String[] args)
{
String str = "Recharge of Rs.196.00 for 9055668800 is successful.";
Pattern r = Pattern.compile("Rs.[0-9.]+");
Matcher m = r.matcher(str);
double sumTotal = 0;
if (m.find()) {
System.out.println("Amount: " + m.group(0).substring(3));
sumTotal += Double.parseDouble(m.group(0).substring(3));
}
}
Output:
Amount: 196.00
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.