txt: ## regexes.md
  ## Chunk 3 of 5
   say ~$0;                # OUTPUT: «c␤»
  }
  ```
  
  If you do not need the captures, using non-capturing `[ ... ]` groups provides the following benefits:
  
  * they more cleanly communicate the regex intent,
  * they make it easier to count the capturing groups that do match, and
  * they make matching a bit faster.
  
  ## [Capture numbers](#Regexes "go to top of document")[§](#Capture_numbers "direct link")
  
  It is stated above that captures are numbered from left to right. While true in principle, this is also an over simplification.
  
  The following rules are listed for the sake of completeness. When you find yourself using them regularly, it's worth considering named captures (and possibly subrules) instead.
  
  Alternations reset the capture count:
  
  ```raku
  / (x) (y)  || (a) (.) (.) /
  # $0  $1      $0  $1  $2
  ```
  
  Example:
  
  ```raku
  if 'abc' ~~ /(x)(y) || (a)(.)(.)/ {
      say ~$1;        # OUTPUT: «b␤»
  }
  ```
  
  If two (or more) alternations have a different number of captures, the one with the most captures determines the index of the next capture:
  
  ```raku
  if 'abcd' ~~ / a [ b (.) || (x) (y) ] (.) / {
      #                 $0     $0  $1    $2
      say ~$2;            # OUTPUT: «d␤»
  }
  ```
  
  Captures can be nested, in which case they are numbered per level; level 0 gets to use the capture variables, but it will become a list with the rest of the levels behaving as elements of that list
  
  ```raku
  if 'abc' ~~ / ( a (.) (.) ) / {
      say "Outer: $0";                # OUTPUT: «Outer: abc␤»
      say "Inner: $0[0] and $0[1]";   # OUTPUT: «Inner: b and c␤»
  }
  ```
  
  These capture variables are only available outside the regex.
  
  ```raku
  # !!WRONG!! The $0 refers to a capture *inside* the second capture
  say "11" ~~ /(\d) ($0)/; # OUTPUT: «Nil␤»
  
  ```
  
  In order to make them available inside the Regexes, you need to insert a code block behind the match; this code block may be empty if there's nothing meaningful to do:
  
  ```raku
  # CORRECT: $0 is saved into a variable outside the second capture
  # before it is used inside
  say "11" ~~ /(\d) {} :my $c = $0; ($c)/; # OUTPUT: «｢11｣␤ 0 => ｢1｣␤ 1 => ｢1｣␤»
  say "Matched $c"; # OUTPUT: «␤Matched 1␤»
  
  ```
  
  This code block *publishes* the capture inside the regex, so that it can be assigned to other variables or used for subsequent matches
  
  ```raku
  say "11" ~~ /(\d) {} $0/; # OUTPUT: «｢11｣␤ 0 => ｢1｣␤»
  
  ```
  
  `:my` helps scoping the `$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 regex. This can be used for debugging inside regular expressions, for instance:
  
  ```raku
  my $paragraph="line\nline2\nline3";
  $paragraph ~~ rx| :my $counter = 0; ( \V* { ++$counter } ) *%% \n |;
  say "Matched $counter lines"; # OUTPUT: «Matched 3 lines␤»
  ```
  
  Since `:my` blocks are simply declarations, the match variable `$/` or numbered matches such as `$0` will not be available in them unless they are previously *published* by inserting the empty block (or any block):
  
  ```raku
  "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:
  
  ```raku
  "aba" ~~ / (a) {say "Check so far ", ~$/} b :my $c = ~$0; /;
  # OUTPUT: «Check so far a␤»
  say "Capture $c"; # OUTPUT: «Capture a␤»
  
  ```
  
  The `:our`, similarly to [`our`](/syntax/our) in classes, can be used in [`Grammar`](/type/Grammar)s to declare variables that can be accessed, via its fully qualified name, from outside the grammar:
  
  ```raku
  grammar HasOur {
      token TOP {
          :our $our = 'Þor';
          $our \s+ is \s+ mighty
      }
  }
  
  say HasOur.parse('Þor is mighty'); # OUTPUT: «｢Þor is mighty｣␤»
  say $HasOur::our;                  # OUTPUT: «Þor␤»
  
  ```
  
  Once the parsing has been done successfully, we use the FQN name of the `$our` variable to access its value, that can be none other than `Þor`.
  
  ## [Named captures](#Regexes "go to top of document")[§](#Named_captures "direct link")
  
  Instead of numbering captures, you can also give them names. The generic, and slightly verbose, way of naming captures is like this:
  
  ```raku
  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:
  
  ```raku
  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:
  
  ```raku
  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](/language/regexes#Subrules) section.
  
  ## [Capture markers: `<( )>`](#Regexes "go to top of document")[§](#Capture_markers:_<(_)> "direct link")
  
  A `<(` token indicates the start of the match's overall capture, while the corresponding `)>` token indicates its endpoint. The `<(` is similar to other languages \K to discard any matches found before the `\K`.
  
  ```raku
  say 'abc' ~~ / a <( b )> c/;            # OUTPUT: «｢b｣␤»
  say 'abc' ~~ / <(a <( b )> c)>/;        # OUTPUT: «｢bc｣␤»
  ```
  
  As in the example above, you can see `<(` sets the start point and `)>` sets the endpoint; since they are actually independent of each other, the inner-most start point wins (the one attached to `b`) and the outer-most end wins (the one attached to `c`).
  
  # [Substitution](#Regexes "go to top of document")[§](#Substitution "direct link")
  
  Regular expressions can also be used to substitute one piece of text for another. You can use this for anything, from correcting a spelling error (e.g., replacing 'Perl Jam' with 'Pearl Jam'), to reformatting an ISO8601 date from `yyyy-mm-ddThh:mm:ssZ` to `mm-dd-yy h:m {AM,PM}` and beyond.
  
  Just like the search-and-replace editor's dialog box, the `s/ / /` operator has two sides, a left and right side. The left side is where your matching expression goes, and the right side is what you want to replace it with.
  
  ## [Lexical conventions](#Regexes "go to top of document")[§](#Lexical_conventions_0 "direct link")
  
  Substitutions are written similarly to matching, but the substitution operator has both an area for the regex to match, and the text to substitute:
  
  ```raku
  s/replace/with/;           # a substitution that is applied to $_
  $str ~~ s/replace/with/;   # a substitution applied to a scalar
  
  ```
  
  The substitution operator allows delimiters other than the slash:
  
  ```raku
  s|replace|with|;
  s!replace!with!;
  s,replace,with,;
  ```
  
  Note that neither the colon `:` nor balancing delimiters such as `{}` or `()` can be substitution delimiters. Colons clash with adverbs such as `s:i/Foo/bar/` and the other delimiters are used for other purposes.
  
  If you use balancing curly braces, square brackets, or parentheses, the substitution works like this instead:
  
  ```raku
  s[replace] = 'with';
  ```
  
  The right-hand side is now a (not quoted) Raku expression, in which `$/` is available as the current match:
  
  ```raku
  $_ = 'some 11 words 21';
  s:g[ \d+ ] =  2 * $/;
  .say;                    # OUTPUT: «some 22 words 42␤»
  ```
  
  Like the `m//` operator, whitespace is ignored in the regex part of a substitution.
  
  ## [Replacing string literals](#Regexes "go to top of document")[§](#Replacing_string_literals "direct link")
  
  The simplest thing to replace is a string literal. The string you want to replace goes on the left-hand side of the substitution operator, and the string you want to replace it with goes on the right-hand side; for example:
  
  ```raku
  $_ = 'The Replacements';
  s/Replace/Entrap/;
  .say;                    # OUTPUT: «The Entrapments␤»
  ```
  
  Alphanumeric characters and the underscore are literal matches, just as in its cousin the `m//` operator. All other characters must be escaped with a backslash `\` or included in quotes:
  
  ```raku
  $_ = 'Space: 1999';
  s/Space\:/Party like it's/;
  .say                        # OUTPUT: «Party like it's 1999␤»
  ```
  
  Note that the matching restrictions generally only apply to the left-hand side of the substitution expression, but some special characters or combinations of them may need to be escaped in the right-hand side (RHS). For example
  
  ```raku
  $_ = 'foo';
  s/foo/\%(/;
  .say        # OUTPUT: «%(␤»
  ```
  
  or escape the '(' instead for the same result
  
  ```raku
  s/foo/%\(/;
  .say        # OUTPUT: «%(␤»
  ```
  
  but using either character alone does not require escaping. Forward slashes will need to be escaped, but escaping alphanumeric characters will cause them to be ignored. (NOTE: This RHS limitation was only recently noticed and this is not yet an exhaustive list of all characters or character pairs that require escapes for the RHS.)
  
  By default, substitutions are only done on the first match:
  
  ```raku
  $_ = 'There can be twly two';
  s/tw/on/;                     # replace 'tw' with 'on' once
  .say;                         # OUTPUT: «There can be only two␤»
  ```
  
  ## [Wildcards and character classes](#Regexes "go to top of document")[§](#Wildcards_and_character_classes "direct link")
  
  Anything that can go into the `m//` operator can go into the left-hand side of the substitution operator, including wildcards and character classes. This is handy when the text you're matching isn't static, such as trying to match a number in the middle of a string:
  
  ```raku
  $_ = "Blake's 9";
  s/\d+/7/;         # replace any sequence of digits with '7'
  .say;             # OUTPUT: «Blake's 7␤»
  ```
  
  Of course, you can use any of the `+`, `*` and `?` modifiers, and they'll behave just as they would in the `m//` operator's context.
  
  ## [Capturing groups](#Regexes "go to top of document")[§](#Capturing_groups "direct link")
  
  Just as in the match operator, capturing groups are allowed on the left-hand side, and the matched contents populate the `$0`..`$n` variables and the `$/` object:
  
  ```raku
  $_ = '2016-01-23 18:09:00';
  s/ (\d+)\-(\d+)\-(\d+) /today/;   # replace YYYY-MM-DD with 'today'
  .say;                             # OUTPUT: «today 18:09:00␤»
  "$1-$2-$0".say;                   # OUTPUT: «01-23-2016␤»
  "$/[1]-$/[2]-$/[0]".say;          # OUTPUT: «01-23-2016␤»
  ```
  
  Any of these variables `$0`, `$1`, `$/` can be used on the right-hand side of the operator as well, so you can manipulate what you've just matched. This way you can separate out the `YYYY`, `MM` and `DD` parts of a date and reformat them into `MM-DD-YYYY` order:
  
  ```raku
  $_ = '2016-01-23 18:09:00';
  s/ (\d+)\-(\d+)\-(\d+) /$1-$2-$0/;    # transform YYYY-MM-DD to MM-DD-YYYY
  .say;                                 # OUTPUT: «01-23-2016 18:09:00␤»
  ```
  
  Named capture can be used too:
  
  ```raku
  $_ = '2016-01-23 18:09:00';
  s/ $<y>=(\d+)\-$<m>=(\d+)\-$<d>=(\d+) /$<m>-$<d>-$<y>/;
  .say;                                 # OUTPUT: «01-23-2016 18:09:00␤»
  ```
  
  Since the right-hand side is effectively a regular Raku interpolated string, you can reformat the time from `HH:MM` to `h:MM {AM,PM}` like so:
  
  ```raku
  $_ = '18:38';
  s/(\d+)\:(\d+)/{$0 % 12}\:$1 {$0 < 12 ?? 'AM' !! 'PM'}/;
  .say;                                 # OUTPUT: «6:38 PM␤»
  ```
  
  Using the modulo `%` operator above keeps the sample code under 80 characters, but is otherwise the same as `$0 < 12 ?? $0 !! $0 - 12`. When combined with the power of the Parser Expression Grammars that **really** underlies what you're seeing here, you can use "regular expressions" to parse pretty much any text out there.
  
  ## [Common adverbs](#Regexes "go to top of document")[§](#Common_adverbs "direct link")
  
  The full list of adverbs that you can apply to regular expressions can be found elsewhere in this document ([section Adverbs](#Adverbs)), but the most common are probably `:g` and `:i`.
  
  * Global adverb `:g`
  
  Ordinarily, matches are only made once in a given string, but adding the `:g` modifier overrides that behavior, so that substitutions are made everywhere possible. Substitutions are non-recursive; for example:
  
  ```raku
  $_ = q{I can say "banana" but I don't know when to stop};
  s:g/na/nana,/;    # substitute 'nana,' for 'na'
  .say;             # OUTPUT: «I can say "banana,nana," but I don't ...␤»
  ```
  
  Here, `na` was found twice in the original string and each time there was a substitution. The substitution only applied to the original string, though. The resulting string was not impacted.
  
  * Insensitive adverb `:i`
  
  Ordinarily, matches are case-sensitive. `s/foo/bar/` will only match `'foo'` and not `'Foo'`. If the adverb `:i` is used, though, matches become case-insensitive.
  
  ```raku
  $_ = 'Fruit';
  s/fruit/vegetable/;
  .say;                          # OUTPUT: «Fruit␤»
  
  s:i/fruit/vegetable/;
  .say;                          # OUTPUT: «vegetable␤»
  ```
  
  For more information on what these adverbs are actually doing, refer to the [section Adverbs](#Adverbs) section of this document.
  
  These are just a few of the transformations you can apply with the substitution operator. Some of the simpler uses in the real world include removing personal data from log files, editing MySQL timestamps into PostgreSQL format, changing copyright information in HTML files and sanitizing form fields in a web application.
  
  As an aside, novices to regular expressions often get overwhelmed and think that their regular expression needs to match every piece of data in the line, including what they want to match. Write just enough to match the data you're looking for, no more, no less.
  
  ## [`S///` non-destructive substitution](#Regexes "go to top of document")[§](#S///_non-destructive_substitution "direct link")
  
  ```raku
  say S/o .+ d/new/ with 'old string';      # OUTPUT: «new string␤»
  S:g/« (.)/$0.uc()/.say for <foo bar ber>; # OUTPUT: «Foo␤Bar␤Ber␤»
  ```
  
  `S///` uses the same semantics as the `s///` operator, except it leaves the original string intact and *returns the resultant string* instead of `$/` (`$/` still being set to the same values as with `s///`).
  
  **Note:** since the result is obtained as a return value, using this operator with the `~~` smartmatch operator is a mistake and will issue a warning. To execute the substitution on a variable that isn't the `$_` this operator uses, alias it to `$_` with `given`, `with`, or any other way. Alternatively, use the [`.subst` method](/routine/subst).
  
  # [Tilde for nesting structures](#Regexes "go to top of document")[§](#Tilde_for_nesting_structures "direct link")
  
  The `~` operator is a helper for matching nested subrules with a specific terminator as the goal. It is designed to be placed between an opening and closing delimiter pair, like so:
  
  ```raku
  / '(' ~ ')' <expression> /
  ```
  
  However, it mostly ignores the left argument, and operates on the next two atoms (which may be quantified). Its operation on those next two atoms is to "twiddle" them so that they are actually matched in reverse order. Hence the expression above, at first blush, is merely another way of writing:
  
  ```raku
  / '(' <expression> ')' /
  ```
  
  Using `~` keeps the separators closer together but beyond that, when it rewrites the atoms it also inserts the apparatus that will set up the inner expression to recognize the terminator, and to produce an appropriate error message if the inner expression does not terminate on the required closing atom. So it really does pay attention to the left delimiter as well, and it actually rewrites our example to something more like:
  
  ```raku
  $<OPEN> = '(' <SETGOAL: ')'> <expression> [ $GOAL || <FAILGOAL> ]
  
  ```
  
  FAILGOAL is a special method that can be defined by the user and it will be called on parse failure:
  
  ```raku
  grammar A { token TOP { '[' ~ ']' \w+  };
              method FAILGOAL($goal) {
                  die "Cannot find $goal near position {self.pos}"
              }
  }
  
  say A.parse: '[good]';  # OUTPUT: «｢[good]｣␤»
  A.parse: '[bad';        # will throw FAILGOAL exception
  CATCH { default { put .^name, ': ', .Str } };
  # OUTPUT: «X::AdHoc: Cannot find ']'  near position 4␤»
  ```
  
  Note that you can use this construct to set up expectations for a closing construct even when there's no opening delimiter:
  
  ```raku
  "3)"  ~~ / <?> ~ ')' \d+ /;  # OUTPUT: «｢3)｣»
  "(3)" ~~ / <?> ~ ')' \d+ /;  # OUTPUT: «｢3)｣»
  ```
  
  Here `<?>` successfully matches the null string.
  
  The order of the regex capture is original:
  
  ```raku
  "abc" ~~ /a ~ (c) (b)/;
  say $0; # OUTPUT: «｢c｣␤»
  say $1; # OUTPUT: «｢b｣␤»
  ```
  
  # [Recursive Regexes](#Regexes "go to top of document")[§](#Recursive_Regexes "direct link")
  
  You can use `<~~>` to recursively invoke the current Regex from within the Regex. This can be extremely helpful for matching nested data structures. For example, consider this Regex:
  
  ```raku
  / '(' <-[()]>* ')' || '('[ <-[()]>* <~~> <-[()]>* ]* ')' /
  ```
  
  This says "match **either** an open parentheses, followed by zero or more non-parentheses characters, followed by a close parentheses **or** an open parentheses followed by zero or more non-parentheses characters, followed by *another match for this Regex*, followed by zero or more non-parentheses characters, followed by a close parentheses." This Regex allows you to match arbitrarily many nested parentheses, as show below:
  
  ```raku
  my $paren = rx/ '(' <-[()]>* ')' || '('[ <-[()]>* <~~> <-[()]>* ]* ')' /;
  say 'text' ~~ $paren;                            # OUTPUT: «Nil␤»
  say '(1 + 1) = 2' ~~ $paren;                     # OUTPUT: «｢(1 + 1)｣␤»
  say '(1 + (2 × 3)) = 7' ~~ $paren;               # OUTPUT: «｢(1 + (2 × 3))｣␤»
  say '((5 + 2) × 6) = 42 (the answer)' ~~ $paren  # OUTPUT: «｢((5 + 2) × 6)｣␤»
  ```
  
  Note that the last expression shown above does *not* match all the way to the final `)`, as would have happened with `/'('.*')'/`, nor does it match only to the first `)`. Instead, it correctly matches to the close parentheses paired with the first opening parentheses, an effect that is very difficult to duplicate without recursive regexes.
  
  When using recursive regexes (as with any other recursive data structure) you should be careful to avoid infinite recursion, which will cause your program to hang or crash.
  
  # [Subrules](#Regexes "go to top of document")[§](#Subrules "direct link")
  
  Just like you can put pieces of code into subroutines, you can also put pieces of regex into named rules.
  
  ```raku
  my regex line { \N*\n }
  if "abc\ndef" ~~ /<line> def/ {
      say "First line: ", $<line>.chomp;      # OUTPUT: «First line: abc␤»
  }
  ```
  
  A named regex can be declared with `my regex named-regex { body here }`, and called with `<named-regex>`. At the same time, calling a named regex installs a named capture with the same name.
  
  To give the capture a different name from the regex, use the syntax `<capture-name=named-regex>`. If no capture is desired, a leading dot or ampersand will suppress it: `<.named-regex>` if it is a method declared in the same class or grammar, `<&named-regex>` for a regex declared in the same lexical context.
  
  Here's more complete code for parsing `ini` files:
  
  ```raku
  my regex header { \s* '[' (\w+) ']' \h* \n+ }
  my regex identifier  { \w+ }
  my regex kvpair { \s* <key=identifier> '=' <value=identifier> \n+ }
  my regex section {
      <header>
      <kvpair>*
  }
  
  my $contents = q:to/EOI/;
      [passwords]
          jack=password1
          joy=muchmoresecure123
      [quotas]
          jack=123
          joy=42
  EOI
  
  my %config;
  if $contents ~~ /<section>*/ {
      for $<section>.list -> $section {
          my %section;
          for $section<kvpair>.list -> $p {
              %section{ $p<key> } = ~$p<value>;
          }
          %config{ $section<header>[0] } = %section;
      }
  }
  say %config.raku;
  
  # OUTPUT: «{:passwords(${:jack("password1"), :joy("muchmoresecure123")}),
  #           :quotas(${:jack("123"), :joy("42")})}»
  ```
  
  Named regexes can and should be grouped in [grammars](/language/grammars). A list of predefined subrules is [here](#Predefined_character_classes).
  
  # [Regex interpolation](#Regexes "go to top of document")[§](#Regex_interpolation "direct link")
  
  Instead of using a literal pattern for a regex match, you can use a variable that holds that pattern. This variable can then be 'interpolated' into a regex, such that its appearance in the regex is replaced with the pattern that it holds. The advantage of using interpolation this way, is that the pattern need not be hardcoded in the source of your Raku program, but may instead be variable and generated at runtime.
  
  There are four different ways of interpolating a variable into a regex as a pattern, which may be summarized as follows:
  
  | Syntax | Description |
  | --- | --- |
  | $variable | Interpolates stringified contents of variable literally. |
  | $(code) | Runs Raku code inside the regex, and interpolates the stringified return value literally. |
  | <$variable> | Interpolates stringified contents of variable as a regex. |
  | <{code}> | Runs Raku code inside the regex, and interpolates the stringified return value as a regex. |
  
  Instead of the `$` sigil, you may use the `@` sigil for array interpolation. See below for how this works.
  
  Let's start with the first two syntactical forms: `$variable` and `$(code)`. These forms will interpolate the stringified value of the variable or the stringified return value of the code literally, provided that the respective value isn't a [`Regex`](/type/Regex) object. If the value is a [`Regex`](/type/Regex), it will not be stringified, but instead be interpolated as such. 'Literally' means *strictly literally*, that is: as if the respective stringified value is quoted with a basic `Q` string [`Q[...]`](/language/quoting#Literal_strings:_Q). Consequently, the stringified value will not itself undergo any further interpolation.
  
  For `$variable` this means the following:
  
  ```raku
  my $string   = 'Is this a regex or a string: 123\w+False$pattern1 ?';
  my $pattern1 = 'string';
  my $pattern2 = '\w+';
  my $number   = 123;
  my $regex    = /\w+/;
  
  say $string.match: / 'string' /;                      #  [1] OUTPUT: «｢string｣␤»
  say $string.match: / $pattern1 /;                     #  [2] OUTPUT: «｢string｣␤»
  say $string.match: / $pattern2 /;                     #  [3] OUTPUT: «｢\w+｣␤»
  say $string.match: / $regex /;                        #  [4] OUTPUT: «｢Is｣␤»
  say $string.match: / $number /;                       #  [5] OUTPUT: «｢123｣␤»
  ```
  
  In this example, the statements `[1]` and `[2]` are equivalent and meant to illustrate a plain case of regex interpolation. Since unescaped/unquoted alphabetic characters in a regex match literally, the single quotes in the regex of statement `[1]` are functionally redundant; they have merely been included to emphasize the correspondence between the first two statements. Statement `[3]` unambiguously shows that the string pattern held by `$pattern2` is interpreted literally, and not as a regex. In case it would have been interpreted as a regex, it would have matched the first word of `$string`, i.e. `｢Is｣`, as can be seen in statement `[4]`. Statement `[5]` shows how the stringified number is used as a match pattern.
  
  This code exemplifies the use of the `$(code)` syntax:
  
  ```raku
  my $string   = 'Is this a regex or a string: 123\w+False$pattern1 ?';
  my $pattern1 = 'string';
  my $pattern3 = 'gnirts';
  my $pattern4 = '$pattern1';
  my $bool     = True;
  my sub f1    { return Q[$pattern1] };
  
  say $string.match: / $pattern3.flip /;                #  [6] OUTPUT: «Nil␤»
  say $string.match: / "$pattern3.flip()" /;            #  [7] OUTPUT: «｢string｣␤»
  say $string.match: / $($pattern3.flip) /;             #  [8] OUTPUT: «｢string｣␤»
  say $string.match: / $([~] $pattern3.comb.reverse) /; #  [9] OUTPUT: «｢string｣␤»
  say $string.match: / $(!$bool) /;                     # [10] OUTPUT: «｢False｣␤»
  
  say $string.match: / $pattern4 /;                     # [11] OUTPUT: «｢$pattern1｣␤»
  say $string.match: / $(f1) /;                         # [12] OUTPUT: «｢$pattern1｣␤»
  ```
  
  Statement `[6]` does not work as probably intended. To the human reader, the dot `.` may seem to represent the [method call operator](/language/operators#methodop_.), but since a dot is not a valid character for an [ordinary identifier](/language/syntax#Ordinary_identifiers), and given the regex context, the compiler will parse it as the regex wildcard [.](/language/regexes#Wildcards) that matches any character. The apparent ambiguity may be resolved in various ways, for instance through the use of straightforward [string interpolation](/language/quoting#Interpolation:_qq) from the regex as in statement `[7]` (note that the inclusion of the call operator `()` is key here), or by using the second syntax form from the above table as in statement `[8]`, in which case the match pattern `string` first emerges as the return value of the `flip` method call. Since general Raku code may be run from within the parentheses of `$( )`, the same effect can also be achieved with a bit more effort, like in statement `[9]`. Statement `[10]` illustrates how the stringified version of the code's return value (the Boolean value `False`) is matched literally.
  
  Finally, statements `[11]` and `[12]` show how the value of `$pattern4` and the return value of `f1` are *not* subject to a further round of interpolation. Hence, in general, after possible stringification, `$variable` and `$(code)` provide for a strictly literal match of the variable or return value.
  
  Now consider the second two syntactical forms from the table above: `<$variable>` and `<{code}>`. These forms will stringify the value of the variable or the return value of the code and interpolate it as a regex. If the respective value is a [`Regex`](/type/Regex), it is interpolated as such:
  
  ```raku
  my $string         = 'Is this a regex or a string: 123\w+$x ?';
  my $pattern1       = '\w+';
  my $number         = 123;
  my sub f1          { return /s\w+/ };
  
  say $string.match: / <$pattern1>  /;                  # OUTPUT: «｢Is｣␤»
  say $string.match: / <$number>    /;                  # OUTPUT: «｢123｣␤»
  say $string.match: / <{ f1 }>     /;                  # OUTPUT: «｢string｣␤»
  ```
  
  Importantly, 'to interpolate as a regex' means to interpolate/insert into the target regex without protective quoting. Consequently, if the value of the variable `$variable1` is itself of the form `$variable2`, evaluation of `<$variable1>` or `<{ $variable1 }>` inside a target regex `/.../` will cause the target regex to assume the form `/$variable2/`. As described above, the evaluation of this regex will then trigger further interpolation of `$variable2`:
  
  ```raku
  my $string    = Q[Mindless \w+ $variable1 $variable2];
  my $variable1 = Q[\w+];
  my $variable2 = Q[$variable1];
  my sub f1     { return Q[$variable2] };
  
  # /<{ f1 }>/ ==> /$variable2/ ==> / '$variable1' /
  say $string.match: / <{ f1 }>     /; # OUTPUT: «｢$variable1｣␤»
  
  # /<$variable2>/ ==> /$variable1/ ==> / '\w+' /
  say $string.match: /<$variable2>/;   # OUTPUT: «｢\w+｣␤»
  
  # /<$variable1>/ ==> /\w+/
  say $string.match: /<$variable1>/;   # OUTPUT: «｢Mindless｣␤»
  ```
  
  When an array variable is interpolated into a regex, the regex engine handles it like a `|` alternative of the regex elements (see the documentation on [embedded lists](/language/regexes#Quoted_lists_are_LTM_matches), above). The interpolation rules for individual elements are the same as for scalars, so strings and numbers match literally, and [`Regex`](/type/Regex) objects match as regexes. Just as with ordinary `|` interpolation, the longest match succeeds:
  
  ```raku
  my @a = '2', 23, rx/a.+/;
  say ('b235' ~~ /  b @a /).Str;      # OUTPUT: «b23␤»
  ```
  
  If you have an expression that evaluates to a list, but you do not want to assign it to an @-sigiled variable first, you can interpolate it with `@(code)`. In this example, both regexes are equivalent:
  
  ```raku
  my %h = a => 1, b => 2;
  my @a = %h.keys;
  say S:g/@(%h.keys)/%h{$/}/ given 'abc';    # OUTPUT: «12c>
  say S:g/@a/%h{$/}/ given 'abc';            # OUTPUT: «12c>
  ```
  
  The use of hashes in regexes is reserved.
  
  ## [Regex Boolean condition check](#Regexes "go to top of document")[§](#Regex_Boolean_condition_check "direct link")
  
  The special operator `<?{}>` allows the evaluation of a Boolean expression that can perform a semantic evaluation of the match before the regular expression continues. In other words, it is possible to check in a Boolean context a part of a regular expression and therefore invalidate the whole match (or allow it to continue) even if the match succeeds from a syntactic point of