3

So i have this String:

val line = "Displaying elements 1 - 4 of 4 in total"

And i want to to parse the total amount: 4 in this case.

This is what i have try:

val line = "Displaying elements 1 - 4 of 4 in total"
val pattern = "\\d".r
println(pattern.findAllMatchIn(line))
david hol
  • 1,272
  • 7
  • 22
  • 44
  • `line.split(' ')(6)` 'Some people, when confronted with a problem, think "I know, I'll use regular expressions.' Now they have two problems.'' - Jamie Zawinski – The Archetypal Paul Jul 11 '16 at 11:00

2 Answers2

3

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

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
2

You can let greed eat up the line until last number.

.*\b(\d+)

See demo at regex101

If you expect decimal number, add a lookbehind and modify to .*\b(?<![.,])(\d[\d.,]*)

Community
  • 1
  • 1
bobble bubble
  • 16,888
  • 3
  • 27
  • 46