Home > front end >  Regex FindAll not printing results Kotlin
Regex FindAll not printing results Kotlin

Time:04-23

I have a program that is using ML Kit to use Text recognition on a document and I am taking that data and only printing the prices. So I am taking the Text Recognition String and passing it through the regex below:

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

I have tested the Regex formula on another website and it grabs all the right data. However it is printing nothing. When it gets to the reg.findAll(rec) part matches = kotlin.sequences.GeneratorSequence@bd56ff3 and prices = "".

CodePudding user response:

You can use

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()

See the online demo. Notes:

  • """...""" is a triple quoted string literal where backslashes are parsed as literal \ chars and are not used to form string escape sequences
  • \$ - in a triple quoted string literal defines a \$ regex escape that matches a literal $ char
  • [0-9]*\.[0-9]{2} matches zero or more digits, . and two digits.

Note that you may use \p{Sc} to match any currency chars, not just $.

If you want to make sure no other digit follows the two fractional digits, add (?![0-9]) at the end of your regex.

  • Related