regex Regex Interpolation

Documentation for regex Regex Interpolation, assembled from the following types:

language documentation Regexes

From Regexes

(Regexes) regex Regex Interpolation

If you want to build a regex using a pattern given at runtime, regex interpolation is what you are looking for.

There are four ways you can interpolate a string into regex as a pattern. That is using $pattern, $($pattern), <$pattern> or <{$pattern.method}>.

If the variable to be interpolated is statically typed as a Str or str (like $pattern0 and $pattern2 are below) and only interpolated literally (like the first example below), than the compiler can optimize that and it runs much faster.

my Str $text = 'camelia';
my Str $pattern0 = 'camelia';
my     $pattern1 = 'ailemac';
my str $pattern2 = '\w+';
say $text ~~ / $pattern0 /;                # OUTPUT: «「camelia」␤» 
say $text ~~ / $($pattern0/;             # OUTPUT: «「camelia」␤» 
say $text ~~ / $($pattern1.flip) /;        # OUTPUT: «「camelia」␤» 
say 'ailemacxflip' ~~ / $pattern1.flip /;  # OUTPUT: «「ailemacxflip」␤» 
say '\w+' ~~ / $pattern2 /;                # OUTPUT: «「\w+」␤» 
say '\w+' ~~ / $($pattern2/;             # OUTPUT: «「\w+」␤» 
say $text ~~ / <{$pattern1.flip}> /;       # OUTPUT: «「camelia」␤» 
# say $text ~~ / <$pattern1.flip> /;       # !!Compile Error!! 
say $text ~~ / <$pattern2> /;              # OUTPUT: «「camelia」␤» 
say $text ~~ / <{$pattern2}> /;            # OUTPUT: «「camelia」␤» 

Note that the first two syntax interpolate the string lexically, while <$pattern> and <{$pattern.method}> causes implicit EVAL, which is a known trap.

When an array variable is interpolated into a regex, the regex engine handles it like a | alternative of the regex elements. The interpolation rules for individual elements are the same as for scalars, so strings and numbers match literally, and /type/Regex objects match as regexes. Just as with ordinary | interpolation, the longest match succeeds:

my @a = '2'23, rx/a.+/;
say ('b235' ~~ /  b @a /).Str;      # OUTPUT: «b23» 

The use of hash variables in regexes is preserved.