Wednesday, April 13, 2011

Perl Regex Tutorial: Find the Index and Position of a Match

use strict;
use warnings;

my $line = "foo 123 bar";

# --- Method 1: Using pos() and length() ---
# The 'g' (global) modifier is used here so that pos() knows where the match ended.

if ($line =~ m{(\d+)}g) {
    # pos() returns the index position immediately *after* the match.
    # By subtracting the length of the matched string ($1), we get the start index.
    my $pos = pos($line) - length($1);
    print "Start position using pos(): $pos\n";   
}

# --- Method 2: Using the pre-match variable ($`) ---
# We reset the variable for the second example.
$line = "foo 123 bar";

if ($line =~ m{(\d+)}g) {
    # $` is a special Perl variable that contains everything BEFORE the matched string.
    # The length of this preceding string is exactly equal to the starting index of the match.
    my $pos = length($`);
    print "Start position using \$`: $pos\n";
}

No comments: