http://qs321.pair.com?node_id=795660


in reply to Re: Regexp not capturing in named subrules
in thread Regexp not capturing in named subrules

I guess I was just surprised to find this something that's more possible in Ruby-1.9. I'll still probably end up just translating to a proper parser but it was easy to use the regexp engine to start with. The below snippet is equivalent to my perl but does return the capture.

require 'pp' re = %r{ # Grammar rules go here (?: (?<thing>.+) ){0} # Invoke grammar here \g<thing> } m = re.match( 'text' ) puts m['thing'] # puts "text\n"

Replies are listed 'Best First'.
Re^3: Regexp not capturing in named subrules
by ikegami (Patriarch) on Sep 16, 2009 at 16:57 UTC
    (?<thing>.+) never matched "text" (backtracking occurred), so it's clearly a major bug in ruby if your code showed it did.

      For clarity, the regex expands to the equivalent of:

      re = %r{ (?: (?<thing>.­+) ){0} (?<thing>.­+) }

      So, yes, (?<thing>.+) did match. It is just that the first instance didn't match. In Perl, %+ only records the captures of the first instance.

      - tye        

      No, you misread. \g<thing> in Ruby-1.9's oniguruma works like (?&thing) in perl 5.10. It's a subroutine call. The grammar section (?: ... ){0} creates the subroutines and I just call an entry point later.

      ⠤⠤ ⠙⠊⠕⠞⠁⠇⠑⠧⠊

        The grammar section (?: ... ){0} creates the subroutines...
        I'm really confused. Did you invent that construct yourself (which looks broken to me) or is it something special-cased in recent grammars (away from its pointless purpose) and recommended in some document I haven't read yet?

        Because if I was writing a regex engine, I'd actually turn {0} into a fatal error, with the invoker needing a clue-bat.

        -- Randal L. Schwartz, Perl hacker

        The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119.