In Regexes§
See primary documentation in context for 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 square brackets in the above example, which don't usually capture, will now capture its grouping with the given name.
The access to the named capture, $<myname>
, is a shorthand for indexing the match object as a hash, in other words: $/{ 'myname' }
or $/<myname>
.
We can also use parentheses in the above example, but they will work exactly the same as square brackets. The captured group will only be accessible by its name as a key from the match object and not from its position in the list with $/[0]
or $0
.
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 by using named regex as discussed in the Subrules section.