0

.* means any character, so why is the .*? needed in the following?

str.gsub(/\#{(.*?)}/) {eval($1)}
Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
Ponnusamy
  • 87
  • 1
  • 1
  • 6

1 Answers1

7

.* is a greedy match, whereas .*? is a non-greedy match. See this link for a quick tutorial on them. Greedy matches will match as much as they can, while non-greedy matches will match as little as they can.

In this example, the greedy variant grabs everything between the first { and the last } (the last closing brace):

'start #{this is a match}{and so is this} end'.match(/\#{(.*)}/)[1]
# => "this is a match}{and so is this"

while the non-greedy variant reads as little as it needs to make the match, so it only reads between the first { and the first successive }.

'start #{this is a match}{and so is this} end'.match(/\#{(.*?)}/)[1]
# => "this is a match"
sawa
  • 165,429
  • 45
  • 277
  • 381
Chris Heald
  • 61,439
  • 10
  • 123
  • 137