class Regex is Method { }

A regex is a kind of pattern that describes a set of strings. The process of finding out whether a given string is in the set is called matching. The result of such a matching is a Match object, which evaluates to True in Boolean context if the string is in the set.

A regex is typically constructed by a regex literal

rx/ ^ab /;      # describes all strings starting with 'ab' 
/ ^ ab /;       # same 
rx/ \d ** 2/;   # describes all strings containing at least two digits

A named regex can be defined with the regex declarator followed by its definition in curly braces. Since any regex does Callable introspection requires referencing via &-sigil.

my regex R { \N };
say &R.^name# OUTPUT: «Regex␤»

To match a string against a regex, you can use the smartmatch operator:

my $match = 'abc' ~~ rx/ ^ab /;
say $match.Bool;                # OUTPUT: «True␤» 
say $match.orig;                # OUTPUT: «abc␤» 
say $match.Str;                 # OUTPUT: «ab␤» 
say $match.from;                # OUTPUT: «0␤» 
say $match.to;                  # OUTPUT: «2␤»

Or you can evaluate the regex in Boolean context, in which case it matches against the $_ variable

$_ = 'abc';
if / ^ab / {
    say '"abc" begins with "ab"';
}
else {
    say 'This is a weird alternative Universe';
}

Methods§

method ACCEPTS§

multi method ACCEPTS(Regex:D: Mu --> Match:D)
multi method ACCEPTS(Regex:D: @)
multi method ACCEPTS(Regex:D: %)

Matches the regex against the argument passed in. If the argument is Positional, it returns the first successful match of any list item. If the argument is Associative, it returns the first successful match of any key. Otherwise it interprets the argument as a Str and matches against it.

In the case of Positional and Associative matches, Nil is returned on failure.

method Bool§

multi method Bool(Regex:D: --> Bool:D)

Matches against the caller's $_ variable, and returns True for a match or False for no match.

Typegraph§

Type relations for Regex
raku-type-graph Regex Regex Method Method Regex->Method Mu Mu Any Any Any->Mu Callable Callable Code Code Code->Any Code->Callable Block Block Block->Code Routine Routine Routine->Block Method->Routine

Expand chart above