2016-02-27 27 views
0

在構建一個android應用程序中,我想從收件箱消息中僅提取數值(Rs.875)並將它們全部添加。 我該怎麼做,請給點意見。如何從字符串中提取數字值

示例:消息將如下所示 - 1>爲9055668800充值Rs.196成功。使用免費應用即時充值預付費手機。 2>嗨,我們已收到付款2000.000與ref.no.NF789465132。敬請期待,同時我們確認您的預訂。

我只能從文本中計算出金額。

+0

要提取的所有數值或只是一個數值? – Mrunal

+0

@Mrunal只是所有消息的金額(Rs.200),我必須將所有這些金額相加並生成一個總金額。 – Prathik

回答

1

您可以這樣做:您可以使用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 
+0

簡單而完美不像我的回答 – Pragnani

+0

@PragnaniKinnera謝謝先生! –

+0

@BahramdunAdil你的問題是什麼?爲什麼你保持低調投票的其他答案?這是荒唐的。 – user2004685

1

這裏是一個沒有正則表達式:

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); 

,輸出是

總:2196.0

-1

如果您只想從給定的字符串中提取充值金額,那麼您可以使用正則表達式,如Rs.[0-9.]+。然後可以將它解析爲整數或雙精度來總結它。

下面是一個簡單的代碼片段:

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)); 
    } 
} 

輸出:

Amount: 196.00 
+0

這是最好的解決方案,但您可以使用'while'循環來代替'if'子句來檢查所有正確捕獲的事件。 –

+0

這個答案沒有意義。它應該被寫爲評論。 –

+0

@Praveen真的嗎?那麼其餘的答案是如何有意義的。 – user2004685