Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Luke Buśk
21,598 PointsHelp me understand regex backreference in Ruby, im a little confused.
Im having trouble understanding backreference in Ruby. There is a particular example from StackOverflow that i cant get a grasp of.
s = /(..) [cs]\1/.match("The cat sat in the hat")
puts s
This code returns "at sat". Now i know that regexp group which is in parentheses captures the last match, so in this example it will be "at". But why the result is "at sat" and it for example ignores a match near the end of the sentence in the word "hat"? There is "at" too.
Also when i play with different letter classes i either get no match or some other weird errors. When i put sentences that have words that repeat, then it works.
Anyway, why it picks up "at" after the s when we use \1 ? Can someone try to explain this? I read a bit of regex tutorials and stuff but its still too hard for me to understand.
1 Answer
Maciej Czuchnowski
36,441 PointsOK, here's how I understand it after doing some reading:
(..) [cs]\1 - two characters, a space, a 'c' or 's' and then again the same characters that were captured by the previous group (by the (..), in this case - the 'at').
This is the only section of this string that matches the criteria. hat does not match here in any way.
You can experiment here: http://rubular.com/r/HN5a86Oiui
This shed some light on the problem for me: http://www.regular-expressions.info/backref.html
Luke Buśk
21,598 PointsLuke Buśk
21,598 PointsI guess i understand it now, final match is "at sat", and not just "at" as i thought. Damn i was dumb lol. Its super easy to solve when You put code like this:
1314564
and use this regex /(\d)\d\1/ . That way we can see if there is a match for 131 because first digit matches "1", second digit matches "3" and \1 backreferences to the first decimal which was saved as "1" so it matches 131. Great tool for checking if words or numbers repeat in any pattern.
I know its obvious but maybe it will help someone in the future so i decided to post it.
Thanks/Dziekuje :D