regex Named captures

Documentation for regex Named captures, assembled from the following types:

language documentation Regexes

From Regexes

(Regexes) regex Named captures

Instead of numbering captures, you can also give them names. The generic, and slightly verbose, way of naming captures is like this:

if 'abc' ~~ / $<myname> = [ \w+ ] / {
    say ~$<myname>      # OUTPUT: «abc␤» 

The access to the named capture, $<myname>, is a shorthand for indexing the match object as a hash, in other words: $/{ 'myname' } or $/<myname>.

Named captures can also be nested using regular capture group syntax:

if 'abc-abc-abc' ~~ / $<string>=( [ $<part>=[abc] ]* % '-' ) / {
    say ~$<string>;          # OUTPUT: «abc-abc-abc␤» 
    say ~$<string><part>;    # OUTPUT: «abc abc abc␤» 
    say ~$<string><part>[0]; # OUTPUT: «abc␤» 

Coercing the match object to a hash gives you easy programmatic access to all named captures:

if 'count=23' ~~ / $<variable>=\w+ '=' $<value>=\w+ / {
    my %h = $/.hash;
    say %h.keys.sort.join: '';        # OUTPUT: «value, variable␤» 
    say %h.values.sort.join: '';      # OUTPUT: «23, count␤» 
    for %h.kv -> $k$v {
        say "Found value '$v' with key '$k'";
        # outputs two lines: 
        #   Found value 'count' with key 'variable' 
        #   Found value '23' with key 'value' 

A more convenient way to get named captures is discussed in the Subrules section.