【问题标题】:Extract amount in cents from currency within text从文本中的货币中提取以美分为单位的金额
【发布时间】:2012-12-28 11:27:08
【问题描述】:

假设我有任意文本,其中包含货币值,如下所示:

The price today is $1,234.56! Don't miss out!

我想将美分数提取为int,即:

123456

一些标准:

  • 000 的逗号是可选的
  • 价格低于 $1,000,000.00
  • $ 始终存在
  • 小数部分始终存在

我尝试过使用 Pattern 和 Matcher,但看起来太乱了。

执行此操作的最简单代码是什么?

【问题讨论】:

  • $ 符号是否一直存在?

标签: java regex parsing


【解决方案1】:

试试

    String s = "The price today is $1,234.56! Don't miss out!";
    Pattern p = Pattern.compile("\\$(((\\d+,?\\d++)|(\\d++))\\.?\\d\\d)");  
    Matcher m = p.matcher(s);
    m.find();
    Long cents = Long.parseLong(m.group(1).replaceAll("[,.]", ""));
    System.out.println(cents);

打印

123456

【讨论】:

  • 然后将值“$1,234.56”转换为美分,只需用value.replaceAll( "[^\\d]", "" )去除所有非数字字符
  • 这甚至没有回答这个问题。 $1,234.56是多少分钱?还是1234.56
【解决方案2】:

我认为包含解析为 int 的这一行代码尽可能简洁:

int cents = Integer.parseInt(input.replaceAll(".*\\$((\\d+),)?(\\d+)\\.(\\d+).*", "$2$3$4"));

【讨论】:

  • @EvgeniyDorofeev 也足以为这个问题投票吗? :)
猜你喜欢
  • 2021-03-15
  • 2011-11-26
  • 2016-05-21
  • 2019-11-04
  • 2020-12-20
  • 2023-03-29
  • 2011-03-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多