@@ -25,6 +25,10 @@ i.e. a sublanguage or L<I<slang>|/language/slangs>. This page describes this lan
2525regexes can be used to search for text patterns in strings in a process called
2626I<pattern matching>.
2727
28+ Raku regexes can L<interpolate|/language/regexes#Regex_interpolation>
29+ variables or code blocks in several different ways, and can be modified
30+ by a variety of L<adverbs|/language/regexes#Adverbs>.
31+
2832=head1 X<Lexical conventions|Syntax,/ /;Syntax,rx;Syntax,m>
2933
3034Fundamentally, Raku regexes are very much like subroutines: both are code
@@ -1867,94 +1871,6 @@ warning. To execute the substitution on a variable that isn't the C<$_> this
18671871operator uses, alias it to C<$_> with C<given>, C<with>, or any other way.
18681872Alternatively, use the L«C<.subst> method|/routine/subst».
18691873
1870- =head1 X<Tilde for nesting structures|Regexes,tilde;Regexes,~>
1871-
1872- The C<~> operator is a helper for matching nested subrules with a
1873- specific terminator as the goal. It is designed to be placed between
1874- an opening and closing delimiter pair, like so:
1875-
1876- / '(' ~ ')' <expression> /
1877-
1878- However, it mostly ignores the left argument, and operates on the next
1879- two atoms (which may be quantified). Its operation on those next two
1880- atoms is to "twiddle" them so that they are actually matched in
1881- reverse order. Hence the expression above, at first blush, is merely
1882- another way of writing:
1883-
1884- / '(' <expression> ')' /
1885-
1886- Using C<~> keeps the separators closer together but beyond that,
1887- when it rewrites the atoms it also inserts the apparatus that will
1888- set up the inner expression to recognize the terminator, and to
1889- produce an appropriate error message if the inner expression does
1890- not terminate on the required closing atom. So it really does pay
1891- attention to the left delimiter as well, and it actually rewrites
1892- our example to something more like:
1893-
1894- X<|Regexes,SETGOAL>
1895- =begin code :skip-test<incomplete code>
1896- $<OPEN> = '(' <SETGOAL: ')'> <expression> [ $GOAL || <FAILGOAL> ]
1897- =end code
1898-
1899- X<FAILGOAL|Regexes,FAILGOAL> is a special method that can be defined by the user and it
1900- will be called on parse failure:
1901-
1902- grammar A { token TOP { '[' ~ ']' \w+ };
1903- method FAILGOAL($goal) {
1904- die "Cannot find $goal near position {self.pos}"
1905- }
1906- }
1907-
1908- say A.parse: '[good]'; # OUTPUT: «「[good]」»
1909- A.parse: '[bad'; # will throw FAILGOAL exception
1910- CATCH { default { put .^name, ': ', .Str } };
1911- # OUTPUT: «X::AdHoc: Cannot find ']' near position 4»
1912-
1913- Note that you can use this construct to set up expectations for a
1914- closing construct even when there's no opening delimiter:
1915-
1916- "3)" ~~ / <?> ~ ')' \d+ /; # OUTPUT: «「3)」»
1917- "(3)" ~~ / <?> ~ ')' \d+ /; # OUTPUT: «「3)」»
1918-
1919- Here C«<?>» successfully matches the null string.
1920-
1921- The order of the regex capture is original:
1922-
1923- "abc" ~~ /a ~ (c) (b)/;
1924- say $0; # OUTPUT: «「c」»
1925- say $1; # OUTPUT: «「b」»
1926-
1927- =head1 X«Recursive Regexes|Regexes,recursive;Regexes,tilde tilde;Regexes,~~;Regexes,<~~>»
1928-
1929- You can use C«<~~>» to recursively invoke the current Regex from within the
1930- Regex. This can be extremely helpful for matching nested data structures. For
1931- example, consider this Regex:
1932-
1933- / '(' <-[()]>* ')' || '('[ <-[()]>* <~~> <-[()]>* ]* ')' /
1934-
1935- This says "match B<either> an open parenthesis, followed by zero or more
1936- non-parentheses characters, followed by a close parenthesis B<or> an open
1937- parenthesis followed by zero or more non-parentheses characters, followed by
1938- I<another match for this Regex>, followed by zero or more non-parentheses
1939- characters, followed by a close parenthesis." This Regex allows you to match
1940- arbitrarily many nested parentheses, as show below:
1941-
1942- my $paren = rx/ '(' <-[()]>* ')' || '('[ <-[()]>* <~~> <-[()]>* ]* ')' /;
1943- say 'text' ~~ $paren; # OUTPUT: «Nil»
1944- say '(1 + 1) = 2' ~~ $paren; # OUTPUT: «「(1 + 1)」»
1945- say '(1 + (2 × 3)) = 7' ~~ $paren; # OUTPUT: «「(1 + (2 × 3))」»
1946- say '((5 + 2) × 6) = 42 (the answer)' ~~ $paren # OUTPUT: «「((5 + 2) × 6)」»
1947-
1948- Note that the last expression shown above does I<not> match all the
1949- way to the final C<)>, as would have happened with C</'('.*')'/>, nor
1950- does it match only to the first C<)>. Instead, it correctly matches
1951- to the close parenthesis paired with the first opening parenthesis, an
1952- effect that is very difficult to duplicate without recursive regexes.
1953-
1954- When using recursive regexes (as with any other recursive data
1955- structure) you should be careful to avoid infinite recursion, which
1956- will cause your program to hang or crash.
1957-
19581874=head1 X<Subrules|Syntax,regex>
19591875
19601876Just like you can put pieces of code into subroutines, you can also put
@@ -2017,31 +1933,41 @@ list of predefined subrules is L<here|#Predefined_character_classes>.
20171933Instead of using a literal pattern for a regex match, you can use a variable
20181934that holds that pattern. This variable can then be 'interpolated' into a regex,
20191935such that its appearance in the regex is replaced with the pattern that it
2020- holds. The advantage of using interpolation this way, is that the pattern need
1936+ holds. You can also use a block of code, the return value of which may be used
1937+ literally, interpreted as a regex, or interpreted as a Boolean that either
1938+ allows the match or prevents it.
1939+
1940+ The advantage of using interpolation this way, is that the pattern need
20211941not be hardcoded in the source of your Raku program, but may instead be
20221942variable and generated at runtime.
20231943
2024- There are four different ways of interpolating a variable into a regex as a
2025- pattern, which may be summarized as follows:
1944+ There are five different ways of interpolating a variable or code-block into a
1945+ regex as a pattern, which may be summarized as follows:
20261946
20271947=begin table
20281948
2029- Syntax | Description
2030- ===============+===========================================================
2031- $variable | Interpolates stringified contents of variable literally.
2032- ---------------------------------------------------------------------------
2033- $(code) | Runs Raku code inside the regex, and interpolates the
2034- | stringified return value literally.
2035- ---------------------------------------------------------------------------
2036- <$variable> | Interpolates stringified contents of variable as a regex.
2037- ---------------------------------------------------------------------------
2038- <{code}> | Runs Raku code inside the regex, and interpolates the
2039- | stringified return value as a regex.
1949+ Syntax | Description
1950+ ===============+===========================================================
1951+ $variable, | Interpolates stringified contents of variable literally.
1952+ @variable |
1953+ ---------------------------------------------------------------------------
1954+ $(code), | Runs Raku code inside the regex, and interpolates the
1955+ @(code) | stringified return value literally.
1956+ ---------------------------------------------------------------------------
1957+ <$variable> | Interpolates stringified contents of variable as a regex.
1958+ <@variable> |
1959+ ---------------------------------------------------------------------------
1960+ <{code}> | Runs Raku code inside the regex, and interpolates the
1961+ | stringified return value as a regex.
1962+ ---------------------------------------------------------------------------
1963+ <?{code}>, | Evaluates Raku code inside the regex in Boolean context,
1964+ <!{code}> | with result either allowing or preventing the match.
20401965
20411966=end table
20421967
2043- Instead of the C<$> sigil, you may use the C<@> sigil for array interpolation.
2044- See below for how this works.
1968+ The use of hashes in regexes is reserved.
1969+
1970+ =head2 Literal interpolation
20451971
20461972X<|Regexes,$variable>X<|Regexes,$(code)>
20471973Let's start with the first two syntactical forms: C«$variable» and C«$(code)».
@@ -2119,6 +2045,8 @@ interpolation. Hence, in general, after possible stringification, C«$variable»
21192045and C«$(code)» provide for a strictly literal match of the variable or return
21202046value.
21212047
2048+ =head2 Interpolation as a regex
2049+
21222050X«|Regexes,<$variable>»X«|Regexes,<{code}>»
21232051Now consider the second two syntactical forms from the table above:
21242052C«<$variable>» and C«<{code}>». These forms will stringify the value of the
@@ -2180,7 +2108,7 @@ The use of hashes in regexes is reserved.
21802108=head2 Regex Boolean condition check
21812109
21822110X«|Regexes,<?{}>;Regexes,<!{}>»
2183- The special operator C«<?{}>» allows the evaluation of a Boolean expression that
2111+ The fifth syntactical form C«<?{}>» allows the evaluation of a Boolean expression that
21842112can perform a semantic evaluation of the match before the regular expression
21852113continues. In other words, it is possible to check in a Boolean context a part
21862114of a regular expression and therefore invalidate the whole match (or allow it to
@@ -2716,6 +2644,94 @@ say S:samespace/a ./c d/.raku given "a\nb"; # OUTPUT: «"c\nd"»
27162644The C<ss/.../.../> syntactic form is a shorthand for
27172645C<s:samespace/.../.../>.
27182646
2647+ =head1 X<Tilde for nesting structures|Regexes,tilde;Regexes,~>
2648+
2649+ The C<~> operator is a helper for matching nested subrules with a
2650+ specific terminator as the goal. It is designed to be placed between
2651+ an opening and closing delimiter pair, like so:
2652+
2653+ / '(' ~ ')' <expression> /
2654+
2655+ However, it mostly ignores the left argument, and operates on the next
2656+ two atoms (which may be quantified). Its operation on those next two
2657+ atoms is to "twiddle" them so that they are actually matched in
2658+ reverse order. Hence the expression above, at first blush, is merely
2659+ another way of writing:
2660+
2661+ / '(' <expression> ')' /
2662+
2663+ Using C<~> keeps the separators closer together but beyond that,
2664+ when it rewrites the atoms it also inserts the apparatus that will
2665+ set up the inner expression to recognize the terminator, and to
2666+ produce an appropriate error message if the inner expression does
2667+ not terminate on the required closing atom. So it really does pay
2668+ attention to the left delimiter as well, and it actually rewrites
2669+ our example to something more like:
2670+
2671+ X<|Regexes,SETGOAL>
2672+ =begin code :skip-test<incomplete code>
2673+ $<OPEN> = '(' <SETGOAL: ')'> <expression> [ $GOAL || <FAILGOAL> ]
2674+ =end code
2675+
2676+ X<FAILGOAL|Regexes,FAILGOAL> is a special method that can be defined by the user and it
2677+ will be called on parse failure:
2678+
2679+ grammar A { token TOP { '[' ~ ']' \w+ };
2680+ method FAILGOAL($goal) {
2681+ die "Cannot find $goal near position {self.pos}"
2682+ }
2683+ }
2684+
2685+ say A.parse: '[good]'; # OUTPUT: «「[good]」»
2686+ A.parse: '[bad'; # will throw FAILGOAL exception
2687+ CATCH { default { put .^name, ': ', .Str } };
2688+ # OUTPUT: «X::AdHoc: Cannot find ']' near position 4»
2689+
2690+ Note that you can use this construct to set up expectations for a
2691+ closing construct even when there's no opening delimiter:
2692+
2693+ "3)" ~~ / <?> ~ ')' \d+ /; # OUTPUT: «「3)」»
2694+ "(3)" ~~ / <?> ~ ')' \d+ /; # OUTPUT: «「3)」»
2695+
2696+ Here C«<?>» successfully matches the null string.
2697+
2698+ The order of the regex capture is original:
2699+
2700+ "abc" ~~ /a ~ (c) (b)/;
2701+ say $0; # OUTPUT: «「c」»
2702+ say $1; # OUTPUT: «「b」»
2703+
2704+ =head1 X«Recursive Regexes|Regexes,recursive;Regexes,tilde tilde;Regexes,~~;Regexes,<~~>»
2705+
2706+ You can use C«<~~>» to recursively invoke the current Regex from within the
2707+ Regex. This can be extremely helpful for matching nested data structures. For
2708+ example, consider this Regex:
2709+
2710+ / '(' <-[()]>* ')' || '('[ <-[()]>* <~~> <-[()]>* ]* ')' /
2711+
2712+ This says "match B<either> an open parenthesis, followed by zero or more
2713+ non-parentheses characters, followed by a close parenthesis B<or> an open
2714+ parenthesis followed by zero or more non-parentheses characters, followed by
2715+ I<another match for this Regex>, followed by zero or more non-parentheses
2716+ characters, followed by a close parenthesis." This Regex allows you to match
2717+ arbitrarily many nested parentheses, as show below:
2718+
2719+ my $paren = rx/ '(' <-[()]>* ')' || '('[ <-[()]>* <~~> <-[()]>* ]* ')' /;
2720+ say 'text' ~~ $paren; # OUTPUT: «Nil»
2721+ say '(1 + 1) = 2' ~~ $paren; # OUTPUT: «「(1 + 1)」»
2722+ say '(1 + (2 × 3)) = 7' ~~ $paren; # OUTPUT: «「(1 + (2 × 3))」»
2723+ say '((5 + 2) × 6) = 42 (the answer)' ~~ $paren # OUTPUT: «「((5 + 2) × 6)」»
2724+
2725+ Note that the last expression shown above does I<not> match all the
2726+ way to the final C<)>, as would have happened with C</'('.*')'/>, nor
2727+ does it match only to the first C<)>. Instead, it correctly matches
2728+ to the close parenthesis paired with the first opening parenthesis, an
2729+ effect that is very difficult to duplicate without recursive regexes.
2730+
2731+ When using recursive regexes (as with any other recursive data
2732+ structure) you should be careful to avoid infinite recursion, which
2733+ will cause your program to hang or crash.
2734+
27192735=head1 Backtracking
27202736
27212737Raku defaults to L<backtracking|/language/glossary#Backtracking> when evaluating regular expressions.
0 commit comments