Can anybody explain how exactly the back reference works in ruby regular expression? I particularly want to know exactly how (..) grouping works. For example:
s = /(..) [cs]\1/.match("The cat sat in the hat")
puts s
for the code snippet above, the output is: at sat. Why/How is it getting this output ?
Here is what this regular expression means:
Note that after matching a regular expression with a matching group, the special variables
$1($2, etc) will contain what matched.Note also that the
Regexp#matchmethod returns a MatchData object, which contains the string which caused the entire match (“at sat”, aka$&) and then each matching group (“at”, aka$1):