2011-09-28 95 views
7

我從Web服務獲取格式化的金額。它可以以不同的格式並使用不同的貨幣,例如從格式化金額提取貨幣

  • $ 1.10
  • € 1,10
  • 1,10 €
  • EUR 1.10(或許,我不知道我會真正遇到這樣的一個)

我想提取貨幣符號( $),並且如果可能的話,從該符號獲得關聯的Currency對象(Java)。我不需要提取金額,我可以在其他地方找到。從java.util.Currency

+0

接受的SO回答這裏可能會有幫助:http://stackoverflow.com/questions/7116507/arbitrary-currency-string-get-all-parts-separated – Steve

回答

0

getSymbol()方法會幫助你得到的貨幣符號

1

你可以在Joda Money看看,它可能會提供您問題的解決方案。注意:它仍然是0.6版本

3

您可以使用正則表達式來解析您的web服務的結果。您必須過濾所有字符,數字,點和空格除外。這是正則表達式:

String regexp = "[^0-9\\.,\\s]*"; 

第一組匹配結果是貨幣符號(或名稱,例如EUR)。

這裏是我的樣本方法:

public void test() throws Exception { 
    String text = "2.02 $"; 
    String regexp = "[^0-9\\.,\\s]*"; 
    Pattern p = Pattern.compile(regexp); 
    Matcher m = p.matcher(text); 
    while (m.find()) { 
     for (int i = 0; i < m.groupCount() + 1; i++) 
      LOG.info(m.group(i)); 
    } 
} 
+0

拋出異常'(而不是'try/catch/System.out.printStackTrace')+1 – michael667