0

I wrote the following code

val input = """{"user":"foo", "name":"bar"}"""
val regex = """.*(?<="user":)"(.*)".*""".r
regex.findAllIn(input).matchData map{m => m.group(1)} toList

The output is res5: List[String] = List("foo\", \"name\":\"bar")

Now I can easily change my regex to

val regex = """.*(?<="user":)"([^"]+)".*""".r

That's not the point...

But my point is why did the .* grab the entire string? My understanding was that the Regex engine is greedy generous so the regex should have seen that after the (.*) there is a " so the generous part should have kicked in and the regex should have only matched the string foo but it seems that the generous part did not kick in.

Knows Not Much
  • 30,395
  • 60
  • 197
  • 373
  • 3
    `*` is a greedy quantifier, `*?` is its lazy counterpart, use it. – Wiktor Stribiżew May 24 '17 at 17:40
  • Greedy-Generous means it will match as much as possible, then give back as little as it needs to to make the pattern work. `(.*)"` Matches the entire string, then works backward until it finds a `"`. – puhlen May 24 '17 at 17:45
  • 1
    There is no guarantee `.*?` will actually be lazy. Unless you're working with some very repeating delimiters, it's better to be specific. And because Strebnez marks all questions as duplicates, you won't get any good examples of how this is possible. Lesson lost ...\ –  May 24 '17 at 20:06

0 Answers0