Friday, 29 September 2017

ruby - What does this regex `str.gsub(/#{(.*?)}/)` do?





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

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...