Regex Basics
Raku regexes look different from Perl/PCRE: whitespace is insignificant by default, literal strings are quoted, and character classes use <[ ]>.
27.1 Matching
my $text = 'Order 42 shipped on 2025-10-24';
if $text ~~ / \d+ / { say "Found: $/" } # $/ = the Match object; stringifies to the match
if $text ~~ / (\d**4) '-' (\d\d) '-' (\d\d) / {
say "Year: $0, Month: $1, Day: $2"; # positional captures $0, $1, $2
}
if $text ~~ / $<year>=[\d**4] '-' $<month>=[\d\d] / {
say "Year: $<year>, Month: $<month>"; # named captures
}
say $text ~~ m:g/ \d+ /; # all matches (adverb :g)
say $text.comb(/\d+/); # (42 2025 10 24)
say $text.match(/ \d+ /).from; # match position
say so 'Raku' ~~ /:i raku/; # case-insensitive: True
say 'abc' !~~ /\d/; # True
my $rx = rx/ \w+ '@' \w+ '.' \w+ /; # regex object
say 'mail [email protected] now' ~~ $rx;27.2 Syntax Summary (Raku vs PCRE)
'literal text' literal\ text Quoted literals (spaces are insignificant otherwise) Any character including newline Any non-newline character \d \w \s \h \v
Digit, word, whitespace, horizontal/vertical whitespace <[a..z] + [0..9] - [x]> Class set operations
<alpha> <digit> <alnum> <upper> <space> <punct> <xdigit> <ident>
<:Letter> / <:Lu> / <:Script<Greek>> Quantifier: \d4, \d2..4, \d**{$n} Possessive (no backtracking)
Separator modifier: one or more x separated by commas Same, allowing a trailing separator
Alternation with longest-token matching (LTM) Sequential (first-match) alternation Conjunction (both must match) Start/end of string ^ $ with /m Start/end of line Left/right word boundary
<?before x> <!before x> <?after x> <!after x> <{ code }> / <?{ cond }> / { code }
Interpolated regex / assertion / embedded code Comments are allowed in regexes
27.3 Adverbs
:i / :ignorecase :m / :ignoremark Ignore diacritics ('café' ~~ /:m cafe/) :g / :global :s / :sigspace
Whitespace in the pattern matches whitespace (<.ws>) :r / :ratchet
No backtracking (default in tokens/rules) :ov / :overlap :ex / :exhaustive All possible matches :c(n) / :pos(n) Continue / anchor at position n :nth(n), :x(n) nth match / exactly n matches
27.4 Substitution and Transliteration
my $s = 'hello world';
$s ~~ s/world/Raku/; # in-place substitution
$s ~~ s:g/o/0/; # global
say $s; # hell0 Raku
say 'hello world'.subst(/o/, '0', :g); # non-destructive: hell0 w0rld
say 'hello world'.subst(/(\w+)/, { $0.tc }, :g); # Hello World (closure replacement)
my $new = S:g/l/L/ given 'hello'; # S/// returns a new string: heLLo
say 'a-b_c'.trans('-_' => ' '); # a b c
($s = 'banana') ~~ tr/a/A/; # tr in place
say $s; # bAnAnA
say 'Hello World'.subst(/:i hello/, 'Bye');
my $text = 'price: 100 USD';
$text ~~ s/(\d+)/{ $0 * 2 }/; # code in the replacement
say $text; # price: 200 USD