txt: ## regexes.md
  ## Chunk 2 of 5
   top of document")[§](#Quantifiers "direct link")
  
  A quantifier makes the preceding atom match a variable number of times. For example, `a+` matches one or more `a` characters.
  
  Quantifiers bind tighter than concatenation, so `ab+` matches one `a` followed by one or more `b`s. This is different for quotes, so `'ab'+` matches the strings `ab`, `abab`, `ababab` etc.
  
  ## [One or more: `+`](#Regexes "go to top of document")[§](#One_or_more:_+ "direct link")
  
  The `+` quantifier makes the preceding atom match one or more times, with no upper limit.
  
  For example, to match strings of the form `key=value`, you can write a regex like this:
  
  ```raku
  / \w+ '=' \w+ /
  ```
  
  ## [Zero or more: `*`](#Regexes "go to top of document")[§](#Zero_or_more:_* "direct link")
  
  The `*` quantifier makes the preceding atom match zero or more times, with no upper limit.
  
  For example, to allow optional whitespace between `a` and `b` you can write:
  
  ```raku
  / a \s* b /
  ```
  
  ## [Zero or one: `?`](#Regexes "go to top of document")[§](#Zero_or_one:_? "direct link")
  
  The `?` quantifier makes the preceding atom match zero or once.
  
  For example, to match `dog` or `dogs`, you can write:
  
  ```raku
  / dogs? /
  ```
  
  ## [General quantifier: `** min..max`](#Regexes "go to top of document")[§](#General_quantifier:_**_min..max "direct link")
  
  To quantify an atom an arbitrary number of times, use the `**` quantifier, which takes a single [`Int`](/type/Int) or a [`Range`](/type/Range) on the right-hand side that specifies the number of times to match. If a [`Range`](/type/Range) is specified, the end-points specify the minimum and maximum number of times to match.
  
  ```raku
  say 'abcdefg' ~~ /\w ** 4/;      # OUTPUT: «｢abcd｣␤»
  say 'a'       ~~ /\w **  2..5/;  # OUTPUT: «Nil␤»
  say 'abc'     ~~ /\w **  2..5/;  # OUTPUT: «｢abc｣␤»
  say 'abcdefg' ~~ /\w **  2..5/;  # OUTPUT: «｢abcde｣␤»
  say 'abcdefg' ~~ /\w ** 2^..^5/; # OUTPUT: «｢abcd｣␤»
  say 'abcdefg' ~~ /\w ** ^3/;     # OUTPUT: «｢ab｣␤»
  say 'abcdefg' ~~ /\w ** 1..*/;   # OUTPUT: «｢abcdefg｣␤»
  
  ```
  
  Only basic literal syntax for the right-hand side of the quantifier is supported, to avoid ambiguities with other regex constructs. If you need to use a more complex expression, for example, a [`Range`](/type/Range) made from variables, enclose the [`Range`](/type/Range) in curly braces:
  
  ```raku
  my $start = 3;
  say 'abcdefg' ~~ /\w ** {$start .. $start+2}/; # OUTPUT: «｢abcde｣␤»
  say 'abcdefg' ~~ /\w ** {π.Int}/;              # OUTPUT: «｢abc｣␤»
  
  ```
  
  Negative values are treated like zero:
  
  ```raku
  say 'abcdefg' ~~ /\w ** {-Inf}/;     # OUTPUT: «｢｣␤»
  say 'abcdefg' ~~ /\w ** {-42}/;      # OUTPUT: «｢｣␤»
  say 'abcdefg' ~~ /\w ** {-10..-42}/; # OUTPUT: «｢｣␤»
  say 'abcdefg' ~~ /\w ** {-42..-10}/; # OUTPUT: «｢｣␤»
  
  ```
  
  If then, the resultant value is `Inf` or `NaN` or the resultant [`Range`](/type/Range) is empty, non-Numeric, contains `NaN` end-points, or has minimum effective end-point as `Inf`, the `X::Syntax::Regex::QuantifierValue` exception will be thrown:
  
  ```raku
  (try say 'abcdefg' ~~ /\w ** {42..10}/  )
      orelse say ($!.^name, $!.empty-range);
      # OUTPUT: «(X::Syntax::Regex::QuantifierValue True)␤»
  (try say 'abcdefg' ~~ /\w ** {Inf..Inf}/)
      orelse say ($!.^name, $!.inf);
      # OUTPUT: «(X::Syntax::Regex::QuantifierValue True)␤»
  (try say 'abcdefg' ~~ /\w ** {NaN..42}/ )
      orelse say ($!.^name, $!.non-numeric-range);
      # OUTPUT: «(X::Syntax::Regex::QuantifierValue True)␤»
  (try say 'abcdefg' ~~ /\w ** {"a".."c"}/)
      orelse say ($!.^name, $!.non-numeric-range);
      # OUTPUT: «(X::Syntax::Regex::QuantifierValue True)␤»
  (try say 'abcdefg' ~~ /\w ** {Inf}/)
      orelse say ($!.^name, $!.inf);
      # OUTPUT: «(X::Syntax::Regex::QuantifierValue True)␤»
  (try say 'abcdefg' ~~ /\w ** {NaN}/)
      orelse say ($!.^name, $!.non-numeric);
      # OUTPUT: «(X::Syntax::Regex::QuantifierValue True)␤»
  
  ```
  
  ## [Modified quantifier: `%`, `%%`](#Regexes "go to top of document")[§](#Modified_quantifier:_%,_%% "direct link")
  
  To more easily match things like comma separated values, you can tack on a `%` modifier to any of the above quantifiers to specify a separator that must occur between each of the matches. For example, `a+ % ','` will match `a` or `a,a` or `a,a,a`, etc.
  
  `%%` is like `%`, with the difference that it can optionally match trailing delimiters as well. This means that besides `a` and `a,a`, it can also match `a,` and `a,a,`.
  
  The quantifier interacts with `%` and controls the number of overall repetitions that can match successfully, so `a* % ','` also matches the empty string. If you want match words delimited by commas, you might need to nest an ordinary and a modified quantifier:
  
  ```raku
  say so 'abc,def' ~~ / ^ [\w+] ** 1 % ',' $ /;  # OUTPUT: «False␤»
  say so 'abc,def' ~~ / ^ [\w+] ** 2 % ',' $ /;  # OUTPUT: «True␤»
  
  ```
  
  ## [Preventing backtracking: `:`](#Regexes "go to top of document")[§](#Preventing_backtracking:_: "direct link")
  
  One way to prevent [backtracking](/language/regexes#Backtracking) is through the use of the `ratchet` adverb as described [below](/language/regexes#Ratchet). Another more fine-grained way of preventing backtracking in regexes is attaching a `:` modifier to a quantifier:
  
  ```raku
  my $str = "ACG GCT ACT An interesting chain";
  say $str ~~ /<[ACGT\s]>+ \s+ (<[A..Z a..z \s]>+)/;
  # OUTPUT: «｢ACG GCT ACT An interesting chain｣␤ 0 => ｢An interesting chain｣␤»
  say $str ~~ /<[ACGT\s]>+: \s+ (<[A..Z a..z \s]>+)/;
  # OUTPUT: «Nil␤»
  
  ```
  
  In the second case, the "A" in "An" had already been absorbed by the pattern, preventing the matching of the second part of the pattern, after `\s+`. Generally we will want the opposite: prevent backtracking to match precisely what we are looking for.
  
  In most cases, you will want to prevent backtracking for efficiency reasons, for instance here:
  
  ```raku
  say $str ~~ m:g/[(<[ACGT]> **: 3) \s*]+ \s+ (<[A..Z a..z \s]>+)/;
  # OUTPUT:
  # «(｢ACG GCT ACT An interesting chain｣
  # «0 => ｢ACG｣␤»
  # «0 => ｢GCT｣␤»
  # «0 => ｢ACT｣␤»
  # «1 => ｢An interesting chain｣)␤»
  
  ```
  
  Although in this case, eliminating the `:` from behind `**` would make it behave exactly in the same way. The best use is to create *tokens* that will not be backtracked:
  
  ```raku
  $_ = "ACG GCT ACT IDAQT";
  say  m:g/[(\w+:) \s*]+ (\w+) $$/;
  # OUTPUT:
  # «(｢ACG GCT ACT IDAQT｣␤»
  # «0 => ｢ACG｣␤»
  # «0 => ｢GCT｣␤»
  # «0 => ｢ACT｣␤»
  # «1 => ｢IDAQT｣)␤»
  ```
  
  Without the `:` following `\w+`, the *ID* part captured would have been simply `T`, since the pattern would go ahead and match everything, leaving a single letter to match the `\w+` expression at the end of the line.
  
  ## [Greedy versus frugal quantifiers: `?`](#Regexes "go to top of document")[§](#Greedy_versus_frugal_quantifiers:_? "direct link")
  
  By default, quantifiers request a greedy match:
  
  ```raku
  'abababa' ~~ /a .* a/ && say ~$/;   # OUTPUT: «abababa␤»
  
  ```
  
  You can attach a `?` modifier to the quantifier to enable frugal matching:
  
  ```raku
  'abababa' ~~ /a .*? a/ && say ~$/;   # OUTPUT: «aba␤»
  
  ```
  
  You can also enable frugal matching for general quantifiers:
  
  ```raku
  say '/foo/o/bar/' ~~ /\/.**?{1..10}\//;  # OUTPUT: «｢/foo/｣␤»
  say '/foo/o/bar/' ~~ /\/.**!{1..10}\//;  # OUTPUT: «｢/foo/o/bar/｣␤»
  ```
  
  Greedy matching can be explicitly requested with the `!` modifier.
  
  # [Alternation: `||`](#Regexes "go to top of document")[§](#Alternation:_|| "direct link")
  
  To match one of several possible alternatives, separate them by `||`; the first matching alternative wins.
  
  For example, `ini` files have the following form:
  
  ｢text｣ without highlighting
  
  ```
  
  
  ```
  
  [section]
  key = value
  
  
  ```
  
  
  ```
  
  Hence, if you parse a single line of an `ini` file, it can be either a section or a key-value pair and the regex would be (to a first approximation):
  
  ```raku
  / '[' \w+ ']' || \S+ \s* '=' \s* \S* /
  ```
  
  That is, either a word surrounded by square brackets, or a string of non-whitespace characters, followed by zero or more spaces, followed by the equals sign `=`, followed again by optional whitespace, followed by another string of non-whitespace characters.
  
  An empty string as the first branch is ignored, to allow you to format branches consistently. You could have written the previous example as
  
  ```raku
  /
  || '[' \w+ ']'
  || \S+ \s* '=' \s* \S*
  /
  ```
  
  Even in non-backtracking contexts, the alternation operator `||` tries all the branches in order until the first one matches.
  
  # [Longest alternation: `|`](#Regexes "go to top of document")[§](#Longest_alternation:_| "direct link")
  
  In short, in regex branches separated by `|`, the longest token match wins, independent of the textual ordering in the regex. However, what `|` really does is more than that. It does not decide which branch wins after finishing the whole match, but follows the [longest-token matching (LTM) strategy](https://github.com/Raku/old-design-docs/blob/master/S05-regex.pod#Longest-token_matching).
  
  Briefly, what `|` does is this:
  
  * First, select the branch which has the longest declarative prefix.
  
  ```raku
  say "abc" ~~ /ab | a.* /;                 # OUTPUT: «⌜abc⌟␤»
  say "abc" ~~ /ab | a {} .* /;             # OUTPUT: «⌜ab⌟␤»
  say "if else" ~~ / if | if <.ws> else /;  # OUTPUT: «｢if｣␤»
  say "if else" ~~ / if | if \s+   else /;  # OUTPUT: «｢if else｣␤»
  ```
  
  As is shown above, `a.*` is a declarative prefix, while `a {} .*` terminates at `{}`, then its declarative prefix is `a`. Note that non-declarative atoms terminate declarative prefix. This is quite important if you want to apply `|` in a `rule`, which automatically enables `:s`, and `<.ws>` accidentally terminates declarative prefix.
  
  * If it's a tie, select the match with the highest specificity.
  
  ```raku
  say "abc" ~~ /a. | ab { print "win" } /;  # OUTPUT: «win｢ab｣␤»
  ```
  
  When two alternatives match at the same length, the tie is broken by specificity. That is, `ab`, as an exact match, counts as closer than `a.`, which uses character classes.
  
  * If it's still a tie, use additional tie-breakers.
  
  ```raku
  say "abc" ~~ /a\w| a. { print "lose" } /; # OUTPUT: «⌜ab⌟␤»
  ```
  
  If the tie breaker above doesn't work, then the textually earlier alternative takes precedence.
  
  For more details, see [the LTM strategy](https://github.com/Raku/old-design-docs/blob/master/S05-regex.pod#Longest-token_matching).
  
  ## [Quoted lists are LTM matches](#Regexes "go to top of document")[§](#Quoted_lists_are_LTM_matches "direct link")
  
  Using a quoted list in a regex is equivalent to specifying the longest-match alternation of the list's elements. So, the following match:
  
  ```raku
  say 'food' ~~ /< f fo foo food >/;      # OUTPUT: «｢food｣␤»
  ```
  
  is equivalent to:
  
  ```raku
  say 'food' ~~ / f | fo | foo | food /;  # OUTPUT: «｢food｣␤»
  ```
  
  Note that the space after the first `<` is significant here: `<food>` calls the named rule `food` while `< food >` and `< food>` specify quoted lists with a single element, `'food'`.
  
  If the first branch is an empty string, it is ignored. This allows you to format your regexes consistently:
  
  ```raku
  /
  | f
  | fo
  | foo
  | food
  /
  ```
  
  Arrays can also be interpolated into a regex to achieve the same effect:
  
  ```raku
  my @increasingly-edible = <f fo foo food>;
  say 'food' ~~ /@increasingly-edible/;   # OUTPUT: «｢food｣␤»
  ```
  
  This is documented further under [Regex Interpolation](#Regex_interpolation), below.
  
  # [Conjunction: `&&`](#Regexes "go to top of document")[§](#Conjunction:_&& "direct link")
  
  Matches successfully if all `&&`-delimited segments match the same substring of the target string. The segments are evaluated left to right.
  
  This can be useful for augmenting an existing regex. For example if you have a regex `quoted` that matches a quoted string, then `/ <quoted> && <-[x]>* /` matches a quoted string that does not contain the character `x`.
  
  Note that you cannot easily obtain the same behavior with a lookahead, that is, a regex doesn't consume characters, because a lookahead doesn't stop looking when the quoted string stops matching.
  
  ```raku
  say 'abc' ~~ / <?before a> && . /;    # OUTPUT: «Nil␤»
  say 'abc' ~~ / <?before a> . && . /;  # OUTPUT: «｢a｣␤»
  say 'abc' ~~ / <?before a> . /;       # OUTPUT: «｢a｣␤»
  say 'abc' ~~ / <?before a> .. /;      # OUTPUT: «｢ab｣␤»
  
  ```
  
  Just like with `||`, empty first branches are ignored.
  
  # [Conjunction: `&`](#Regexes "go to top of document")[§](#Conjunction:_& "direct link")
  
  Much like `&&` in a Regexes, it matches successfully if all segments separated by `&` match the same part of the target string.
  
  `&` (unlike `&&`) is considered declarative, and notionally all the segments can be evaluated in parallel, or in any order the compiler chooses.
  
  Just like with `||` and `&`, empty first branches are ignored.
  
  # [Anchors](#Regexes "go to top of document")[§](#Anchors "direct link")
  
  Regexes search an entire string for matches. Sometimes this is not what you want. Anchors match only at certain positions in the string, thereby anchoring the regex match to that position.
  
  ## [Start of string and end of string](#Regexes "go to top of document")[§](#Start_of_string_and_end_of_string "direct link")
  
  The `^` anchor only matches at the start of the string:
  
  ```raku
  say so 'karakul'  ~~ /  raku/;    # OUTPUT: «True␤»
  say so 'karakul'  ~~ /^ raku/;    # OUTPUT: «False␤»
  say so 'rakuy'    ~~ /^ raku/;    # OUTPUT: «True␤»
  say so 'raku'     ~~ /^ raku/;    # OUTPUT: «True␤»
  ```
  
  The `$` anchor only matches at the end of the string:
  
  ```raku
  say so 'use raku' ~~ /  raku  /;   # OUTPUT: «True␤»
  say so 'use raku' ~~ /  raku $/;   # OUTPUT: «True␤»
  say so 'rakuy'    ~~ /  raku $/;   # OUTPUT: «False␤»
  ```
  
  You can combine both anchors:
  
  ```raku
  say so 'use raku' ~~ /^ raku $/;   # OUTPUT: «False␤»
  say so 'raku'     ~~ /^ raku $/;   # OUTPUT: «True␤»
  ```
  
  Keep in mind that `^` matches the start of a **string**, not the start of a **line**. Likewise, `$` matches the end of a **string**, not the end of a **line**.
  
  The following is a multi-line string:
  
  ```raku
  my $str = chomp q:to/EOS/;
     Keep it secret
     and keep it safe
     EOS
  
  # 'safe' is at the end of the string
  say so $str ~~ /safe   $/;   # OUTPUT: «True␤»
  
  # 'secret' is at the end of a line, not the string
  say so $str ~~ /secret $/;   # OUTPUT: «False␤»
  
  # 'Keep' is at the start of the string
  say so $str ~~ /^Keep   /;   # OUTPUT: «True␤»
  
  # 'and' is at the start of a line -- not the string
  say so $str ~~ /^and    /;   # OUTPUT: «False␤»
  ```
  
  ## [Start of line and end of line](#Regexes "go to top of document")[§](#Start_of_line_and_end_of_line "direct link")
  
  The `^^` anchor matches at the start of a logical line. That is, either at the start of the string, or after a newline character. However, it does not match at the end of the string, even if it ends with a newline character.
  
  The `$$` anchor matches at the end of a logical line. That is, before a newline character, or at the end of the string when the last character is not a newline character.
  
  To understand the following example, it's important to know that the `q:to/EOS/...EOS` [heredoc](/language/quoting#Heredocs:_:to) syntax removes leading indention to the same level as the `EOS` marker, so that the first, second and last lines have no leading space and the third and fourth lines have two leading spaces each.
  
  ```raku
  my $str = q:to/EOS/;
      There was a young man of Japan
      Whose limericks never would scan.
        When asked why this was,
        He replied "It's because I always try to fit
      as many syllables into the last line as ever I possibly can."
      EOS
  
  # 'There' is at the start of string
  say so $str ~~ /^^ There/;        # OUTPUT: «True␤»
  
  # 'limericks' is not at the start of a line
  say so $str ~~ /^^ limericks/;    # OUTPUT: «False␤»
  
  # 'as' is at start of the last line
  say so $str ~~ /^^ as/;            # OUTPUT: «True␤»
  
  # there are blanks between start of line and the "When"
  say so $str ~~ /^^ When/;         # OUTPUT: «False␤»
  
  # 'Japan' is at end of first line
  say so $str ~~ / Japan $$/;       # OUTPUT: «True␤»
  
  # there's a . between "scan" and the end of line
  say so $str ~~ / scan $$/;        # OUTPUT: «False␤»
  
  # matched at the last line
  say so $str ~~ / '."' $$/;        # OUTPUT: «True␤»
  ```
  
  ## [Word boundary](#Regexes "go to top of document")[§](#Word_boundary "direct link")
  
  To match any word boundary, use `<?wb>`. This is similar to `\b` in other languages. To match the opposite, any character that is not bounding a word, use `<!wb>`. This is similar to `\B` in other languages; `\b` and `\B` will throw an [`X::Obsolete`](/type/X/Obsolete) exception from version 6.d of Raku.
  
  These are both zero-width regex elements.
  
  ```raku
  say "two-words" ~~ / two<?wb>\-<?wb>words /;    # OUTPUT: «｢two-words｣␤»
  say "twowords" ~~ / two<!wb><!wb>words /;     # OUTPUT: «｢twowords｣␤»
  ```
  
  ## [Left and right word boundary](#Regexes "go to top of document")[§](#Left_and_right_word_boundary "direct link")
  
  `<<` matches a left word boundary. It matches positions where there is a non-word character at the left, or the start of the string, and a word character to the right.
  
  `>>` matches a right word boundary. It matches positions where there is a word character at the left and a non-word character at the right, or the end of the string.
  
  These are both zero-width regex elements.
  
  ```raku
  my $str = 'The quick brown fox';
  say so ' ' ~~ /\W/;               # OUTPUT: «True␤»
  say so $str ~~ /br/;              # OUTPUT: «True␤»
  say so $str ~~ /<< br/;           # OUTPUT: «True␤»
  say so $str ~~ /br >>/;           # OUTPUT: «False␤»
  say so $str ~~ /own/;             # OUTPUT: «True␤»
  say so $str ~~ /<< own/;          # OUTPUT: «False␤»
  say so $str ~~ /own >>/;          # OUTPUT: «True␤»
  say so $str ~~ /<< The/;          # OUTPUT: «True␤»
  say so $str ~~ /fox >>/;          # OUTPUT: «True␤»
  ```
  
  You can also use the variants `«` and `»` :
  
  ```raku
  my $str = 'The quick brown fox';
  say so $str ~~ /« own/;          # OUTPUT: «False␤»
  say so $str ~~ /own »/;          # OUTPUT: «True␤»
  ```
  
  To see the difference between `<?wb>` and `«`, `»`:
  
  ```raku
  say "stuff here!!!".subst(:g, />>/, '|');   # OUTPUT: «stuff| here|!!!␤»
  say "stuff here!!!".subst(:g, /<</, '|');   # OUTPUT: «|stuff |here!!!␤»
  say "stuff here!!!".subst(:g, /<?wb>/, '|'); # OUTPUT: «|stuff| |here|!!!␤»
  ```
  
  ## [Summary of anchors](#Regexes "go to top of document")[§](#Summary_of_anchors "direct link")
  
  Anchors are zero-width regex elements. Hence they do not use up a character of the input string, that is, they do not advance the current position at which the regex engine tries to match. A good mental model is that they match between two characters of an input string, or before the first, or after the last character of an input string.
  
  | Anchor | Description | Examples |
  | --- | --- | --- |
  | ^ | Start of string | "⏏two\nlines" |
  | ^^ | Start of line | "⏏two\n⏏lines" |
  | $ | End of string | "two\nlines⏏" |
  | $$ | End of line | "two⏏\nlines⏏" |
  | << or « | Left word boundary | "⏏two ⏏words" |
  | >> or » | Right word boundary | "two⏏ words⏏" |
  | <?wb> | Any word boundary | "⏏two⏏ ⏏words⏏~!" |
  | <!wb> | Not a word boundary | "t⏏w⏏o w⏏o⏏r⏏d⏏s~⏏!" |
  | <?ww> | Within word | "t⏏w⏏o w⏏o⏏r⏏d⏏s~!" |
  | <!ww> | Not within word | "⏏two⏏ ⏏words⏏~⏏!⏏" |
  
  # [Zero-width assertions](#Regexes "go to top of document")[§](#Zero-width_assertions "direct link")
  
  Zero-Width assertions can help you implement your own anchor: it turns another regex into an anchor, making them consume no characters of the input string. There are two variants: lookahead and lookbehind assertions.
  
  Technically, anchors are also zero-width assertions, and they can look both ahead and behind.
  
  ## [Lookaround assertions](#Regexes "go to top of document")[§](#Lookaround_assertions "direct link")
  
  Lookaround assertions, which need a character class in its simpler form, work both ways. They match, but they don't consume a character.
  
  ```raku
  my regex key {^^ <![#-]> \d+ }
  say "333" ~~ &key;                  # OUTPUT: «｢333｣␤»
  say '333$' ~~ m/ \d+ <?[$]>/;       # OUTPUT: «｢333｣␤»
  say '$333' ~~ m/^^ <?[$]> . \d+ /;  # OUTPUT: «｢$333｣␤»
  
  ```
  
  They can be positive or negative: `![]` is negative, while `?[]` is positive; the square brackets will contain the characters or backslashed character classes that are going to be matched.
  
  You can use predefined character classes and Unicode properties directly preceded by the exclamation or interrogation mark to convert them into lookaround assertions.:
  
  ```raku
  say '333' ~~ m/^^ <?alnum> \d+ /;          # OUTPUT: «｢333｣␤»
  say '333' ~~ m/^^ <?:Nd> \d+ /;            # OUTPUT: «｢333｣␤»
  say '333' ~~ m/^^ <!:L> \d+ /;             # OUTPUT: «｢333｣␤»
  say '333' ~~ m/^^ \d+ <!:Script<Tamil>> /; # OUTPUT: «｢33｣␤»
  
  ```
  
  In the first two cases, the corresponding character class matches, but does not consume, the first digit, which is then consumed by the expression; in the third, the negative lookaround assertion behaves in the same way. In the fourth statement the last digit is matched but not consumed, thus the match includes only the first two digits.
  
  ## [Lookahead assertions](#Regexes "go to top of document")[§](#Lookahead_assertions "direct link")
  
  To check that a pattern appears before another pattern, use a lookahead assertion via the `before` assertion. This has the form:
  
  ```raku
  <?before pattern>
  ```
  
  Thus, to search for the string `foo` which is immediately followed by the string `bar`, use the following regexp:
  
  ```raku
  / foo <?before bar> /
  ```
  
  For example:
  
  ```raku
  say "foobar" ~~ / foo <?before bar> /;  # OUTPUT: «foo␤»
  ```
  
  However, if you want to search for a pattern which is **not** immediately followed by some pattern, then you need to use a negative lookahead assertion, this has the form:
  
  ```raku
  <!before pattern>
  ```
  
  In the following example, all occurrences of `foo` which is not before `bar` would match with
  
  ```raku
  say "foobaz" ~~ / foo <!before bar> /;  # OUTPUT: «foo␤»
  ```
  
  Lookahead assertions can be used also with other patterns, like characters ranges, interpolated variables subscripts and so on. In such cases it does suffice to use a `?`, or a `!` for the negate form. For instance, the following lines all produce the very same result:
  
  ```raku
  say 'abcdefg' ~~ rx{ abc <?before def> };        # OUTPUT: «｢abc｣␤»
  say 'abcdefg' ~~ rx{ abc <?[ d..f ]> };          # OUTPUT: «｢abc｣␤»
  my @ending_letters = <d e f>;
  say 'abcdefg' ~~ rx{ abc <?@ending_letters> };   # OUTPUT: «｢abc｣␤»
  ```
  
  Metacharacters can also be used in lookahead or -behind assertions.
  
  ```raku
  say "First. Second" ~~ m:g/ <?after ^^ | "." \s+> <:Lu>\S+ /
  # OUTPUT: «(｢First.｣ ｢Second｣)␤»
  ```
  
  A practical use of lookahead assertions is in substitutions, where you only want to substitute regex matches that are in a certain context. For example, you might want to substitute only numbers that are followed by a unit (like *kg*), but not other numbers:
  
  ```raku
  my @units = <kg m km mm s h>;
  $_ = "Please buy 2 packs of sugar, 1 kg each";
  s:g[\d+ <?before \s* @units>] = 5 * $/;
  say $_;         # OUTPUT: «Please buy 2 packs of sugar, 5 kg each␤»
  ```
  
  Since the lookahead is not part of the match object, the unit is not substituted.
  
  ## [Lookbehind assertions](#Regexes "go to top of document")[§](#Lookbehind_assertions "direct link")
  
  To check that a pattern appears after another pattern, use a lookbehind assertion via the `after` assertion. This has the form:
  
  ```raku
  <?after pattern>
  ```
  
  Therefore, to search for the string `bar` immediately preceded by the string `foo`, use the following regexp:
  
  ```raku
  / <?after foo> bar /
  ```
  
  For example:
  
  ```raku
  say "foobar" ~~ / <?after foo> bar /;   # OUTPUT: «bar␤»
  ```
  
  However, if you want to search for a pattern which is **not** immediately preceded by some pattern, then you need to use a negative lookbehind assertion, this has the form:
  
  ```raku
  <!after pattern>
  ```
  
  Hence all occurrences of `bar` which do not have `foo` before them would be matched by
  
  ```raku
  say "fotbar" ~~ / <!after foo> bar /;    # OUTPUT: «bar␤»
  ```
  
  These are, as in the case of lookahead, zero-width assertions which do not *consume* characters, like here:
  
  ```raku
  say "atfoobar" ~~ / (.**3) .**2 <?after foo> bar /;
  # OUTPUT: «｢atfoobar｣␤ 0 => ｢atf｣␤»
  ```
  
  where we capture the first 3 of the 5 characters before bar, but only if `bar` is preceded by `foo`. The fact that the assertion is zero-width allows us to use part of the characters in the assertion for capture.
  
  # [Grouping and capturing](#Regexes "go to top of document")[§](#Grouping_and_capturing "direct link")
  
  In regular (non-regex) Raku, you can use parentheses to group things together, usually to override operator precedence:
  
  ```raku
  say 1 + 4 * 2;     # OUTPUT: «9␤», parsed as 1 + (4 * 2)
  say (1 + 4) * 2;   # OUTPUT: «10␤»
  ```
  
  The same grouping facility is available in regexes:
  
  ```raku
  / a || b c /;      # matches 'a' or 'bc'
  / ( a || b ) c /;  # matches 'ac' or 'bc'
  ```
  
  The same grouping applies to quantifiers:
  
  ```raku
  / a b+ /;          # matches an 'a' followed by one or more 'b's
  / (a b)+ /;        # matches one or more sequences of 'ab'
  / (a || b)+ /;     # matches a string of 'a's and 'b's, except empty string
  ```
  
  An unquantified capture produces a [`Match`](/type/Match) object. When a capture is quantified (except with the `?` quantifier) the capture becomes a list of [`Match`](/type/Match) objects instead.
  
  ## [Capturing](#Regexes "go to top of document")[§](#Capturing "direct link")
  
  The round parentheses don't just group, they also *capture*; that is, they make the string matched within the group available as a variable, and also as an element of the resulting [`Match`](/type/Match) object:
  
  ```raku
  my $str =  'number 42';
  if $str ~~ /'number ' (\d+) / {
      say "The number is $0";         # OUTPUT: «The number is 42␤»
      # or
      say "The number is $/[0]";      # OUTPUT: «The number is 42␤»
  }
  ```
  
  Pairs of parentheses are numbered left to right, starting from zero.
  
  ```raku
  if 'abc' ~~ /(a) b (c)/ {
      say "0: $0; 1: $1";             # OUTPUT: «0: a; 1: c␤»
  }
  ```
  
  The `$0` and `$1` etc. syntax is shorthand. These captures are canonically available from the match object `$/` by using it as a list, so `$0` is actually syntactic sugar for `$/[0]`.
  
  Coercing the match object to a list gives an easy way to programmatically access all elements:
  
  ```raku
  if 'abc' ~~ /(a) b (c)/ {
      say $/.list.join: ', '  # OUTPUT: «a, c␤»
  }
  ```
  
  ## [Non-capturing grouping](#Regexes "go to top of document")[§](#Non-capturing_grouping "direct link")
  
  The parentheses in regexes perform a double role: they group the regex elements inside and they capture what is matched by the sub-regex inside.
  
  To get only the grouping behavior, you can use square brackets `[ ... ]` which, by default, don't capture.
  
  ```raku
  if 'abc' ~~ / [a||b] (c) / {
     