Core Function Match

From Sputnik Wiki
Jump to: navigation, search
Match( <string>, <pattern>, <offset> )

Contents

Description

Search for the first match of pattern in a string if found return the captures from the pattern.

Parameters

string

The string to evaluate.

pattern

Go read the Patterns section on the Find( ) function to learn how to create and use patterns then come back here to put it to use on this function.

offset

Optional; Specifies where to start the search; its default value is 0 and can be negative.

Return Value

Remarks

This function is pretty much the same a the LUA String.Match() however this one returns start position starting at 0 (LUA's starts at 1) and lowers the end position by 1, Also the Offset begins at 0 here where as in LUA it begins at 1.

This is because in Sputnik chars in a string start at 0 not 1.

Example

Extract substrings by matching patterns.

// Extract as a single string
say match("I have 2 questions for you.", "%d+ %a+");
// Prints
// 2 questions

Same as above but this time using capture groups

printr match("I have 2 questions for you.", "(%d+) (%a+)");
// Prints
// Array
// (
//     [0] => 2
//     [1] => questions
// )

Same as above but this time using the return value directly

my List ($HowMany, $What) = match("I have 2 questions for you.", "(%d+) (%a+)");
say "There are '$HowMany' $What";
// Prints
// There are '2' questions

Same as above mostly

my $final = vsprintf("%d, %s!", match("I have 2 questions for you.", "(%d+) (%a+)"));
say $final;
// Returns
// 2, questions!

Check an e-mail is valid

my $email = 'username@domain.com';
 
if ( match($email, '[A-Za-z0-9%.%%%+%-]+@[A-Za-z0-9%.%%%+%-]+%.%w%w%w?%w?') )
   say "$email IS formatted properly.";
else
   say "$email is NOT formatted properly.";

Match digits

// %d matches a digit
printr match("foo 123 bar", '%d%d%d');
// Prints
// 123

How to match special % and symbols

printr match("%*^", '%%%*%^');
// Prints
// %*^

Capture and return groups

my $date = "04/19/64";
my List ( $m, $d, $y ) = match($date, "(%d+)/(%d+)/(%d+)");
say "Month: $m";
say "Day: $d";
say "Year: $y";
print("19" . $y);
// Prints
// Month: 04
// Day: 19
// Year: 64
// 1964

Match only A-F and 0-9 chars.

say match("ABEF3634", '^[A-F0-9]*$'); // ABEF3634
say match("cat", '^[A-F0-9]*$'); // NULL

Match only ASCII using \x escape with %z

say match("cat", "^[%z\x01-\xFF]*\$"); // cat
say match("こんにちは", "^[%z\x01-\xFF]*\$"); // null

Like all Spuntik match() supports unicode example

// Find everything from こ to は
say match("hello こんにちは!", 'こ.*は'); // こんにちは
Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox