Regex FindAll 不打印结果 Kotlin

Regex FindAll not printing results Kotlin

我有一个程序正在使用 ML Kit 在文档上使用文本识别,我正在获取该数据并仅打印价格。所以我使用文本识别字符串并通过下面的正则表达式传递它:

val reg = Regex("$([0-9]*.[0-9]{2})")
    val matches = reg.findAll(rec)
    val prices = matches.map{it.groupValues[0]}.joinToString()
recogResult.text = prices 

我在另一个网站上测试了 Regex 公式,它获取了所有正确的数据。但是它什么也没打印。当它到达 reg.findAll(rec) 部分 matches = kotlin.sequences.GeneratorSequence@bd56ff3 and prices = "".

您可以使用

val reg = Regex("""$[0-9]*\.[0-9]{2}""")
val matches = reg.findAll("Price: $1234.56 and $1.56")
val prices = matches.map{it.groupValues[0]}.joinToString()

online demo备注:

  • """...""" 是三引号字符串文字,其中反斜杠被解析为文字 \ 字符,不用于形成字符串转义序列
  • $ - 在三重引号字符串文字中定义了一个 $ 正则表达式转义匹配文字 $ char
  • [0-9]*\.[0-9]{2} 匹配零个或多个数字,. 和两个数字。

请注意,您可以使用 \p{Sc} 来匹配任何货币字符,而不仅仅是 $

如果您想确保两位小数后没有其他数字,请在您的正则表达式末尾添加 (?![0-9])