Can I use named groups in a Perl regex to get the results in a hash?

后端 未结 4 2059
死守一世寂寞
死守一世寂寞 2020-12-30 00:12

Is it possible to perform a named-group match in Perl\'s regex syntax as with Python\'s? I always bind the $n values to proper names after matching, so I\'d fin

相关标签:
4条回答
  • 2020-12-30 00:44

    As couple of people said perl 5.10 has named groups.

    But in previous perls you can do something, not as convenient, but relatively nice:

    my %hash;
    @hash{"count", "something_else"} = $string =~ /(\d+)\s*,\s*(\S+)/;
    

    and then you can use:

    $hash{"count"} and $hash{"something_else"}.

    0 讨论(0)
  • 2020-12-30 00:45

    Perl uses (?<NAME>pattern) to specify names captures. You have to use the %+ hash to retrieve them.

    $variable =~ /(?<count>\d+)/;
    print "Count is $+{count}";
    

    This is only supported on Perl 5.10 and higher though.

    0 讨论(0)
  • 2020-12-30 00:56

    As of Perl 5.10, Perl regexes support some Python features, making them Python compatible regexes, I guess. The Python versions have the "P" in them, but all of these work in Perl 5.10. See the perlre documentation for the details:

    Define a named capture buffer. Equivalent to (?<NAME>pattern).

    (?P<NAME>pattern)
    

    Backreference to a named capture buffer. Equivalent to \g{NAME}.

    (?P=NAME)
    

    Subroutine call to a named capture buffer. Equivalent to (?&NAME).

    (?P>NAME)
    

    Although I didn't add the Python-compatibility to the latest edition of Learning Perl, we do cover the new Perl 5.10 features, including named captures.

    0 讨论(0)
  • 2020-12-30 00:58

    AFIK PCRE has named group capturing as:

    (?'NAME'pattern)
    (?<NAME>pattern)
    

    You can find info here.

    0 讨论(0)
提交回复
热议问题