Version: v0.8.1 - Beta.  We welcome contributors & feedback.

String.match

match($regexPattern, $groupNames='') -> string|map

Description

Find the first match for the given regex pattern.

Returns an empty string '' if there is no match.

If there is a match, it will return the matched substring.

'abc 123'.match(rx'abc \d+')
//= 'abc 123'

'abc 123'.match(rx'xyz \d+')
//= ''

// Ignore-case flag
'abc 123'.match(rx'ABC'i)
//= 'abc'

Capture Groups

If the regex pattern contains capture groups defined by parens (...), it will return a Map containing the submatch for each group.

Each group of is assigned a number according to where its left paren ( appears in the pattern.

The key full will contain the full outer match.

The key indexOf contains the index position of each group.

$time = 'Time: 08:23 AM'

$m = $time.match(rx'(\d+):(\d+)')
$m[1]      //= '08'
$m[2]      //= '23'
$m.full    //= '08:23'
$m.indexOf //= { 1: 7, 2: 10, full: 7 }

Group Names

If $groupNames is given a pipe-delimited string of names, those will be used instead of numbers.

$time = 'Time: 08:23 AM'

$time.match(rx'(\d+):(\d+)', 'hour|minute')
$m.hour      //= '08'
$m.minute    //= '23'
$m.full      //= '08:23'
$m.indexOf   //= { hour: 7, minute: 10 }

Using match With if

When you call this method in an if statement, you can use the If-Assign := operator to get the returned result and use it inside the block.

$str = 'abc 123'

if $num := $str.match(rx'\d+') {
    print($num)
    //= '123'
}

See Also