用金钱解析金额和货币代码?

时间:2015-08-19 22:39:37

标签: java

所以我有这些字符串:

“$ 1212,10”
“EUR12,15”
“SEK1500.10”
“50NZD”
“NZ $ 50,00”

我需要将货币代码和金额分成两个独立的变量 我从哪里开始?

1 个答案:

答案 0 :(得分:2)

您可以使用正则表达式。像这样:

Pattern p = Pattern.compile("^(.*?)([0-9.,]+)$");
Matcher m = p.matcher("$1212,10");

if(m.find()){
   String cur = m.group(1);
   String amount = m.group(2);
}

问题更改后的附录:

您可以在此处获取货币代码列表:https://en.wikipedia.org/wiki/ISO_4217

货币符号位于:https://en.wikipedia.org/wiki/Currency_symbol

Jaca通过Currency.class支持货币 http://docs.oracle.com/javase/7/docs/api/java/util/Currency.html

如果存在,您可以将cur字符串转换为正确的货币。您必须使用正确的区域设置才能正常工作。

完成(或多或少):

String YOURSTRING = "SEK1500.10";

Pattern p = Pattern.compile("^(.*?)([0-9.,]+)$");
Matcher m = p.matcher(YOURSTRING);
String cur = null;
String amount = null;

if(m.find()){
    cur = m.group(1);
    amount = m.group(2);
}
else{
    p = Pattern.compile("^([0-9.,]+)(.*)$");
    m = p.matcher(YOURSTRING);

    if(m.find()){
        cur = m.group(2);
        amount = m.group(1);    
    }
    else{
        //no match
    }
}

if (cur!=null){
    Currency foundCurrrency = null;
    for (Currency c : Currency.getAvailableCurrencies()){
        if (c.getSymbol(Locale.ENGLISH).equals(cur)){
            //symbol matches!
            foundCurrrency = c;
            break;
        }
        else if (c.getCurrencyCode().equals(cur)){
            //code matches!
            foundCurrrency = c;
            break;
        }

    }
    if (foundCurrrency!=null){
        //YOU FOUND IT
        System.out.println("found currency: "+foundCurrrency);
        System.out.println("amount: "+amount);

    }
}

注意:" 50,000新西兰元"在大多数情况下不会起作用,因为" NZ $"可能未在您使用的语言环境中定义为符号。也许你需要遍历所有语言环境并测试所有符号以找到你需要的符号。