货币与金额分开

时间:2016-03-21 04:51:23

标签: regex scala currency

所以我想解析包含货币值的字符串,例如:

€579,976
€0
$1.5

目前我只是删除第一个char并尝试解析其余的。

有没有人知道如何以更好的方式做到这一点?

1 个答案:

答案 0 :(得分:2)

您可以使用regular expression来解决该问题。 货币有Unicode Character Property\p{Sc}

用法示例,货币和金额:

val amountAndCurrencyRe = "(\\p{Sc})(.*)".r

val results = amountAndCurrencyRe.findAllIn("""€579,976  
  €0 
  $1.5
  ¥20
""")

results.collect{ 
 case amountAndCurrencyRe(currency,amount) =>
   println(s"Amount:$amount Currency:$currency") 
}.toList

结果:

scala> results.collect{ case amountAndCurrencyRe(currency,amount) => println(s"Amount:$amount Currency:$currency") }.toList
Amount:579,976  Currency:€
Amount:0 Currency:€
Amount:1.5 Currency:$
Amount:20 Currency:¥
res6: List[Unit] = List((), (), (), ())

只需获得金额:

scala> "€579,976  €0 $1.5 ¥20".replaceAll("\\p{Sc}","")
res1: String = 579,976  0 1.5 20