class Match

Result of a successful regex match
class Match is Capture is Cool does NQPMatchRole {}

Match objects are the result of a successful regex match, including any zero-width match. They store a reference to the original string (.orig), positional and named captures, the positions of the start and end of the match in the original string, and a payload referred to as AST (abstract syntax tree), which can be used to build data structures from complex regexes and grammars.

The last match is also stored in the |Variables,$¢ Match object, which is lexically scoped to the regex, that is, only available from within the regular expression, as shown here:

my $c;
    'abc' ~~ /.$${ $c = $¢ }/;
    say $c; # OUTPUT: «「c」␤»

In this example we are running the code among curly braces when the match occurs, in this case the last letter in the string (actually, the last, indicated by the double $, character); $c gets the value of the cursor , which contains the Match; when used with say, the Match is stringified by calling .Str on it. This offers a way of capturing the Match inside a regular expression; outside, you need to use $/

my $c; 'camelia' ~~ /<[ l m ]> {$c = $¢}/;
    say $c; # OUTPUT: «「m」␤»
    say $/; # OUTPUT: «「m」␤»

Note: This feature works only from Raku version 2018.02. It would have returned Nil with any previous version. Alternatively and prior to that version, you could use $/ which, inside the regex, has the same value:

'123' ~~ / (\d) { say $0; say $/; } \d+ /; # OUTPUT: «「1」␤「1」␤ 0 => 「1」␤»

The main difference between $/ and is scope: the latter only has a value inside the regex:

'123' ~~ / (\d) { say $/; say $¢; } \d+ /; # OUTPUT: «「1」␤ 0 => 「1」␤「1」␤ 0 => 「1」␤»
say "¢ → ", $¢, "/ is $/"; ; # OUTPUT: «¢ → Nil/ is 123␤»

Submatches are also Match objects (or lists of Match objects, if the corresponding regex was quantified), so each match object can be seen as the root of a tree of match objects.

A Match object can also hold the result of a match in progress (while the grammar engine is running), in which case the pos method returns the current position. This view on Match objects is only visible if you call code from within a regex.

Note (deprecated): There is a synonym for this class, Cursor|Reference,Cursor, defined as:

my constant Cursor = Match

Initially, it was used to keep track of initial position in regex matches. In current versions, it's an alias for Match.

Methods

method pos

Returns the current position as a string index into Match.target for a regex match in progress:

my $a = 'abcdef';
    $a ~~ /b. {say $/.pos }../;     # OUTPUT: «3␤»

You should not use this method on a finished Match, as the output can be implementation specific or is, in any case, unspecified.

method target

method target()

Returns a string representation of the object against which the regex matches. This is the value that the regex engine works with internally.

my $a = "þor" ~~ /o/;
    say $a.target # OUTPUT: «þor␤»

method chars

method chars()

Returns the numbers of characters in the matched string or 0 if there's been no match.

Returns the same as .Str.chars.

method clone

method clone()

Clones the Match object.

method orig

method orig()

Returns the original input to the regex engine, which is usually a string, but doesn't need to be (could be anything that can be coerced to a string):

42 ~~ /.+/;
    say $/.orig;            # OUTPUT: «42␤»
    say $/.orig.^name;      # OUTPUT: «Int␤»

See method target for a close equivalent that always returns a string.

method from

method from()

Returns the index of the starting position of the match.

method to

method to()

Returns the index of the position next to the end of the match. It will return the match position if the end of the match is negative, and Nil if there has been no match.

method made

method made()

Returns the payload that was set with make.

routine make

method make(Match:D: Mu $payload)
    sub make(Mu $payload)

Sets the .ast attribute, which will be retrieved using .made.

$/.make("your payload here");

That is, it stores an arbitrary payload into the Match object that can later be retrieved via .made method. Since the sub form operates, by default, on $/, that example is equivalent to:

make("your payload here");

This is typically used in a grammar's actions class methods, where a piece of data is stored by one method and then later retrieved by another. It's up to you what data you store. It could be a tree node, result of a calculation, a type object, or a list of values.

The sub form operates on the current Match $/, which can be a convenient shortcut:

method my-action ($/) {
        make "foo: $/";
    }

method actions

method actions(Match:D: --> Mu)

Returns the actions object (if any was set; else Mu) that the grammar used from which this Match object was created.

method ast

Alias for method made.

method Bool

method Bool(Capture:D: --> Bool:D)

Returns True on successful and False on unsuccessful matches. Please note that any zero-width match can also be successful.

say 'abc' ~~ /^/;                   # OUTPUT: «「」␤»
    say $/.from, ' ',  $/.to, ' ', ?$/; # OUTPUT: «0 0 True␤»

method Str

method Str(Match:D: --> Str:D)

Returns the matched text.

"abc123def" ~~ /\d+/;
    say $/.Str;               # OUTPUT: «123␤»

method Int

method Int(Match:D: --> Int:D)

Tries to convert stringified result of the matched text into Int.

say ('12345' ~~ /234/).Int;       # OUTPUT: «234␤»
    say ('12345' ~~ /234/).Int.^name; # OUTPUT: «Int␤»
    # the next line produces a warning about using Nil (result of a no match) in numeric context
    say ('one-two' ~~ /234/).Int;     # OUTPUT: «0␤» # because Nil.Int returns 0

method caps

Returns a list of pairs, with the index or submatch name as key and the submatches as values. The list is ordered by starting position of the submatches.

method chunks

Returns a list of pairs, with the index or submatch name as key and the submatches as values. The list is ordered by starting position of the submatches.

Those parts of the string that were not matched by submatches are interleaved with the other pairs, with the string ~ as key.

method list

Returns a list of positional submatches.

method hash

Returns a hash of named submatches.

method prematch

method prematch(Match:D: --> Str:D)

Returns the part of the original string leading up to the match.

'abcdefg' ~~ /cd/;
    say $/.prematch;          # OUTPUT: «ab␤»
# will return a list of three match objects
    "abc123def" ~~ m:g/\d/;
    say $/.[1].prematch;      # OUTPUT: «abc1␤»

method postmatch

method postmatch(Match:D: --> Str:D)

Returns the part of the original string following the match.

'abcdefg' ~~ /cd/;
    say $/.postmatch;         # OUTPUT: «efg␤»
# will return a list of three match objects
    "abc123def" ~~ m:g/\d/;
    say $/.[1].postmatch;     # OUTPUT: «3def␤»

method replace-with

multi method replace-with(Match:D: Str() $replacement --> Str:D)

Returns the invocant string where the Match object is replaced by $replacement.

my Str $some-string = "Some foo";
    my Match $match = $some-string.match(/foo/);
    my $another-string = $match.replace-with("string"); # «Some string»

infix eqv

multi infix:<eqv>(Match:D \a, Match:D \b)

Returns True if the attributes pos, from and orig for a and b are equal, and if made, Capture::list and Capture::hash are either the same or both undefined.

See Also

class Attribute

Member variable

class Cancellation

Removal of a task from a Scheduler before normal completion

class Channel

Thread-safe queue for sending values from producers to consumers

class CompUnit

CompUnit

class CompUnit::Repository::FileSystem

CompUnit::Repository::FileSystem

class CompUnit::Repository::Installation

CompUnit::Repository::Installation

class Distro

Distribution related information

class Grammar

Formal grammar made up of named regexes

class IO::ArgFiles

Iterate over contents of files specified on command line

class IO::CatHandle

Use multiple IO handles as if they were one

class IO::Handle

Opened file or stream

class IO::Notification

Asynchronous notification for file and directory changes

class IO::Notification::Change

Changes in a file, produced by watch-file

class IO::Path

File or directory path

class IO::Path::Cygwin

IO::Path pre-loaded with IO::Spec::Cygwin

class IO::Path::Parts

IO::Path parts encapsulation

class IO::Path::QNX

IO::Path pre-loaded with IO::Spec::QNX

class IO::Path::Unix

IO::Path pre-loaded with IO::Spec::Unix

class IO::Path::Win32

IO::Path pre-loaded with IO::Spec::Win32

class IO::Pipe

Buffered inter-process string or binary stream

class IO::Socket::Async

Asynchronous socket in TCP or UDP

class IO::Socket::Async::ListenSocket

A tap for listening TCP sockets

class IO::Socket::INET

TCP Socket

class IO::Spec

Platform specific operations on file and directory paths

class IO::Spec::Cygwin

Platform specific operations on file and directory paths for Cygwin

class IO::Spec::QNX

Platform specific operations on file and directory paths QNX

class IO::Spec::Unix

Platform specific operations on file and directory paths for POSIX

class IO::Spec::Win32

Platform specific operations on file and directory paths for Windows

class IO::Special

Path to special I/O device

class Kernel

Kernel related information

class Lock

A low-level, re-entrant, mutual exclusion lock

class Lock::ConditionVariable

Condition variables used in locks

class Pod::Block

Block in a Pod document

class Pod::Block::Code

Verbatim code block in a Pod document

class Pod::Block::Comment

Comment in a Pod document

class Pod::Block::Declarator

Declarator block in a Pod document

class Pod::Block::Named

Named block in a Pod document

class Pod::Block::Para

Paragraph in a Pod document

class Pod::Block::Table

Table in a Pod document

class Pod::Defn

Pod definition list

class Pod::FormattingCode

Pod formatting code

class Pod::Heading

Heading in a Pod document

class Pod::Item

Item in a Pod enumeration list

class Proc

Running process (filehandle-based interface)

class Proc::Async

Running process (asynchronous interface)

class Promise

Status/result of an asynchronous computation

class Regex

String pattern

class Semaphore

Control access to shared resources by multiple threads

class Supplier

Live Supply factory

class Supplier::Preserving

Cached live Supply factory

class Supply

Asynchronous data stream with multiple subscribers

class Tap

Subscription to a Supply

class Thread

Concurrent execution of code (low-level)

class ThreadPoolScheduler

Scheduler that distributes work among a pool of threads

class Unicode

Unicode related information

class VM

Raku Virtual Machine related information

The Camelia image is copyright 2009 by Larry Wall. "Raku" is trademark of the Yet Another Society. All rights reserved.