10

I'm new to Regular Expressions in Ruby, and I can't seem to find any solid documentation on what \k<name+0> means. It's the +0 part that I'm not getting.

Here's an example - this Regexp matches palindromes:

\A(?<p>(?:(?<l>\w)\g<p>\k<l+0>|\w))\z

When I remove the +0 in \k<l+0> it no longer matches correctly.
My tests:

>> /\A(?<p>(?:(?<l>\w)\g<p>\k<l+0>|\w))\z/.match "aabbcdcbbaa" 
#=> #<MatchData "aabbcdcbbaa" p:"aabbcdcbbaa" l:"c">

>> /\A(?<p>(?:(?<l>\w)\g<p>\k<l>|\w))\z/.match "aabbcdcbbaa" 
#=> nil

All I've done is remove the +0. I haven't yet found any documentation or example of this, can anyone point me in the right direction?

1
  • Great question. It's introduced me to the wonderful world of \g<...>. Commented Sep 10, 2016 at 16:01

1 Answer 1

11

The \k<l+0> works together with the (?<l>\w)

The match of (?<l>\w) is stored in the capturing group named 'l'

\k<l+0> Matches the same text that was matched by the named capturing group 'l' when it was at the same recursion level as this backreference is now

5
  • 1
    Awesome! Also, it's +0. Are there any other functions like +1 or anything? Commented Sep 10, 2016 at 10:47
  • @Cᴀʟʟᴏᴅᴀᴄɪᴛʏ +0 is the same recursion level, +1 is one level deeper, -1 is one level less deep
    – Andie2302
    Commented Sep 10, 2016 at 15:52
  • 1
    I don't doubt what you say, but I'd like to find a reference for +0, preferably in the Ruby docs, but in the Oniguruma docs otherwise. Commented Sep 10, 2016 at 15:58
  • @CarySwoveland I found some documentation for this here and here if you're still interested. Commented Sep 16, 2016 at 0:03
  • Callodacity, thanks. Yes, that's what I was looking for. I should have checked that site as I use it for other reference purposes. Commented Sep 16, 2016 at 0:38

Not the answer you're looking for? Browse other questions tagged or ask your own question.