.*
means any character, so why is the .*?
needed in the following?
str.gsub(/\#{(.*?)}/) {eval($1)}
Answer
.*
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"
No comments:
Post a Comment