所以我想解析包含货币值的字符串,例如:
€579,976
€0
$1.5
目前我只是删除第一个char
并尝试解析其余的。
有没有人知道如何以更好的方式做到这一点?
答案 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