Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 find it more convenient to do it in the regex itself if it's possible.

Python does it like so:

>>> import re >>> regex = re.compile(r'(?P<count>\d+)') >>> match = regex.match('42') >>> print match.groupdict() {'count': '42'} 

I know the ?P indicates that it's a Python-specific regex feature, but I'm hoping it's in Perl in a different way or was added later on. Is there any way to get a result hash in a similar manner in Perl?

like image 587
cdleary Avatar asked Nov 14 '08 01:11

cdleary


People also ask

How do I match a group in regex?

Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters "d", "o", and "g".

What is \W in Perl regex?

18, the vertical tab; \w means the 63 characters [A-Za-z0-9_] ; and likewise, all the Posix classes such as [[:print:]] match only the appropriate ASCII-range characters.

How does regex group work?

What is Group in Regex? A group is a part of a regex pattern enclosed in parentheses () metacharacter. We create a group by placing the regex pattern inside the set of parentheses ( and ) . For example, the regular expression (cat) creates a single group containing the letters 'c', 'a', and 't'.

How do I match a pattern in Perl?

m operator in Perl is used to match a pattern within the given text. The string passed to m operator can be enclosed within any character which will be used as a delimiter to regular expressions.


2 Answers

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.

like image 100
Leon Timmermans Avatar answered Oct 04 '22 23:10

Leon Timmermans


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.

like image 22
brian d foy Avatar answered Oct 04 '22 21:10

brian d foy