The regex API in Scala only provides a method to get the first match (findFirstIn
) or all matches (findAllIn
), but not the last match. Most languages have a similar set of regex methods because to get the last regex match you may easily get all matches but only refer to the last one.
Same in Scala:
val line = "Displaying invoices 1 - 4 of 9 in total"
val pattern = """\d+""".r
println(pattern.findAllIn(line).toList.last)
// => 9
As an alternative, for the current scenario, you may also use
val line = "Displaying invoices 1 - 4 of 4 in total"
val pattern = """\d+(?=\s*in total)""".r
println(pattern.findFirstIn(line))
See IDEONE demo.
The \d+(?=\s*in total)
pattern will find 1 or more digits (\d+
) that are followed with 0+ whitespaces and in total
substring (see the positive lookahead (?=\s*in total)
).