Core\Regex\Match::offset
$match->offset(): intReturns the position in the text where a match starts.
The first character of the text is at position 0. The position counts characters, the same way a person counts them, and not bytes. So an accented letter or an emoji before the match counts as one. Every Core\Str method counts positions the same way, so you can give this position to Core\Str::slice or to the from option of Core\Regex::match.
The position is where the whole match starts, which is also where group 0 starts.
The examples show where a word starts, a position after accented letters, and marking the place of an error in a line of input.
Return value
Returns int. The position of the first character of the match. A match at the start of the text is at 0.
Examples
Where a word starts
<?nvs// Shows how to find the position where a match starts.
// "total" starts after "Sum of all: ", which has 12 characters. This prints 12.var $m = Core\Regex::match('Sum of all: total 99', 'total');echo $m?->offset() ?? -1, "\n";
// A match at the start of the text is at position 0.echo Core\Regex::match('total 99', 'total')?->offset() ?? -1, "\n";120Characters not bytes
<?nvs// Shows that the position counts characters, so accented letters and emoji count as one.
// "Café 🎉 " has 7 characters, so the number starts at position 7.// The same text has 11 bytes.string $line = 'Café 🎉 2026';var $m = Core\Regex::match($line, '\d+');if ($m != null) { echo 'position: ', $m->offset(), "\n"; // `Core\Str::slice` counts the same way, so this prints "Café 🎉 ". echo 'before: [', Core\Str::slice($line, 0, $m->offset()), "]\n";}position: 7before: [Café 🎉 ]Mark an error in the input
<?nvs// Shows how to point at the first character that is not allowed in a line of input.
array<string> $codes = ['AB-1234', 'AB-12x4', 'Ä-1234'];foreach ($codes as string $code) { // The pattern finds the first character that is not a capital letter, a digit or "-". var $bad = Core\Regex::match($code, '[^A-Z0-9-]'); if ($bad == null) { echo $code, " is valid\n"; } else { // The "^" goes under the character at the position that `offset` returns. echo $code, "\n", Core\Str::repeat(' ', $bad->offset() as uint), "^ not allowed\n"; }}AB-1234 is validAB-12x4 ^ not allowedÄ-1234^ not allowed