Search notes:

Perl regular expressions: named groups

#!/usr/bin/perl
use warnings;
use strict;

my $text = 'foo 42 baz';

# Naming a matched portion:
#
$text =~ /(?<num>\d+)/;
print "number found: $+{num}\n";
#
# number found: 42


$text = 'abc foo OF bar and baz IN foo etc';

# Two named groups with the same name (»where«):
#
while ($text =~ /foo OF (?<where>\w+)|(?<where>\w+) IN foo/g) {
  print "where: $+{where}\n";
}
#
# where: bar
# where: baz


$text = 'ab <TAG-ONE>cd efg<TAG-TWO>hi jkl</TAG-TWO>mn opq<TAG-THREE>rst</TAG-THREE>uv</TAG-ONE>wx<TAG-FOUR>yz</TAG-FOUR>';

# Using \k'name' to refer to a named match in the pattern where
# the name was defined.
#
$text =~ m|<(?<tagname>[^>]+)>(?<content>.*)</\k'tagname'|;
print "$+{content}\n";
#
# cd efg<TAG-TWO>hi jkl</TAG-TWO>mn opq<TAG-THREE>rst</TAG-THREE>uv
Github repository about-perl, path: /regular-expressions/named-groups.pl

See also

Perl regular expressions

Index

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php:78 Stack trace: #0 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(78): PDOStatement->execute(Array) #1 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(30): insert_webrequest_('/notes/developm...', 1759407282, '216.73.216.42', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/development/languages/Perl/regular-expressions/named-groups(72): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78