Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (45.3k points)

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?

1 Answer

0 votes
by (16.8k points)

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.

Related questions

0 votes
1 answer
asked Nov 13, 2019 in Java by Nigam (4k points)
0 votes
1 answer
0 votes
1 answer
asked Jul 27, 2019 in AWS by yuvraj (19.1k points)
0 votes
1 answer
asked Nov 12, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.1k users

Browse Categories

...