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))
1
  • 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 Commented Jul 11, 2016 at 11:00

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.,]*)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.