One thing at a time all the time!

Welcome to Rocteur
Friday, April 19 2024 @ 02:47 AM CEST

Can you find the position of what was matched in a regular expression

use the @- and @+ arrays


In addition to what was matched, Perl 5.6.0 also provides the positions of what was matched with the "@-" and "@+" arrays. "$-[0]" is the
position of the start of the entire match and $+[0] is the position of the end. Similarly, "$-[n]" is the position of the start of the $n
match and $+[n] is the position of the end. If $n is undefined, so are "$-[n]" and $+[n]. Then this code

$x = "Mmm...donut, thought Homer";
$x =~ /^(Mmm|Yech)\.\.\.(donut|peas)/; # matches
foreach $expr (1..$#-) {
print "Match $expr: '${$expr}' at position ($-[$expr],$+[$expr])\n";
}

prints

Match 1: 'Mmm' at position (0,3)
Match 2: 'donut' at position (6,11)

perldoc perlretut

FAQ Manager » Perl » Can you find the position of what was matched in a regular expression