如何从格式化价格中提取价值?

时间:2013-09-04 01:03:25

标签: java regex

我想在java中使用正则表达式从价格中提取值。例如,40,250.99美元 我希望表达式输出40250.99。关键是它必须只用正则表达式来完成。我不能做任何字符串连接或其他字符串相关的操作。我尝试了以下但是","弄乱了一切。基本上$ 503.34将产生503.34但$ 40,250.99产量40

String extractionPattern = "[\\$](\\d+(?:\\.\\d{1,2})?)";
String val = "    Executive billings @ $40,250.99 Starting 2013-01-05 with bi weekly";
Pattern  p = Pattern.compile(extractionPattern);
Matcher m = p.matcher(val);
if (m.find())
     System.out.println("Found a match:" + m.group(1));

1 个答案:

答案 0 :(得分:0)

可能有更好的方法可以做到这一点,我会第一个承认我的正则表达式非常基本......

String regExp = "\\$[0-9,\\.]+";
String value = "Executive billings @ $40,250.99 Starting 2013-01-05 with bi weekly";

Pattern pattern = Pattern.compile(regExp);
Matcher matcher = pattern.matcher(value);

// This should result in a list with 1 element of "$40,250.99"
List<String> lstMatches = new ArrayList<String>(5);
while (matcher.find()) {
    lstMatches.add(matcher.group());
}

for (String match : lstMatches) {
    // Strip off the unrqeuired elements...
    match = match.replaceAll("\\$", "");
    match = match.replaceAll(",", "");
    System.out.println(Double.parseDouble(match));
}

您甚至可以使用NumberFormat.getCurrencyInstance().parse(match)将结果解析回double,但这会假设输入符合本地要求......