Skip to content

Commit

Permalink
Merge pull request Raku#1652 from perl6/doc-regex-interpolation
Browse files Browse the repository at this point in the history
Document Regex Interpolation, jnthn++
  • Loading branch information
tisonkun authored Nov 4, 2017
2 parents 8f105bb + 69cdc07 commit 390459d
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions doc/Language/regexes.pod6
Original file line number Diff line number Diff line change
Expand Up @@ -1255,6 +1255,37 @@ list of predefined subrules is listed in
L<S05-regex|https://design.perl6.org/S05.html#Predefined_Subrules> of design
documents.
=head1 X<Regex Interpolation|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 C«$pattern», C«$($pattern)», C«<$pattern>» or
C«<{$pattern.method}>».
my Str $text = 'camelia';
my Str $pattern0 = 'camelia';
my Str $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
C«<$pattern>» and C«<{$pattern.method}>» causes L«implicit EVAL|
/language/traps#<{$x}>_vs_$($x):_Implicit_EVAL», which is a known trap.
=head1 Adverbs
Adverbs modify how regexes work and provide convenient shortcuts for
Expand Down

0 comments on commit 390459d

Please sign in to comment.