Skip to content

Commit

Permalink
Adds examples using backreferences in regexes
Browse files Browse the repository at this point in the history
This closes #1545. Since this part is going to probably be moved dur
to #2890, it will move with them; this seemed the most reasonable part
to document these back references, since it's where they are actually used.
  • Loading branch information
JJ committed Jul 8, 2019
1 parent 2f096dd commit 17a102a
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions doc/Language/regexes.pod6
Original file line number Diff line number Diff line change
Expand Up @@ -1108,6 +1108,7 @@ assigned to other variables or used for subsequent matches
=for code
say "11" ~~ /(\d) {} $0/; # OUTPUT: «「11」␤ 0 => 「1」␤»
X<|:my>
C<:my> helps scoping the C<$c> variable within the regex and beyond; in this
case we can use it in the next sentence to show what has been matched inside the
Expand All @@ -1117,6 +1118,22 @@ regex. This can be used for debugging inside regular expressions, for instance:
$paragraph ~~ rx| :my $counter = 0; ( \V* { ++$counter } ) *%% \n |;
say "Matched $counter lines"; # OUTPUT: «Matched 3 lines␤»
Since C<:my> blocks are simply declarations, the match variable C<$/> or
numbered matches such as C<$0> will not be available in them unless they are
previously I<published> by inserting the empty block (or any block):
=for code
"aba" ~~ / (a) b {} :my $c = $/; /;
say $c; # OUTPUT: «「ab」␤ 0 => 「a」␤»
Any other code block will also reveal the variables and make them available in
declarations:
=for code
"aba" ~~ / (a) {say "Check so far ", ~$/} b :my $c = ~$0; /;
# OUTPUT: «Check so far a␤»
say "Capture $c"; # OUTPUT: «Capture a␤»
X<|:our>
The C<:our>, similarly to L<C<our>|/syntax/our> in classes, can be used in
L<Grammar|/type/Grammar>s to declare variables that can be accessed, via its
Expand Down

0 comments on commit 17a102a

Please sign in to comment.