0

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

str.gsub(/\#{(.*?)}/) {eval($1)}
Andrew Marshall
  • 92,562
  • 20
  • 215
  • 211
Ponnusamy
  • 77
  • 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
  • 160,959
  • 41
  • 265
  • 366
Chris Heald
  • 59,258
  • 10
  • 117
  • 133