Alex Rivera | Logout

How can I find the location of a regex match in Perl?

Asked 2008-09-17T20:37:16.700
36

I need to write a function that receives a string and a regex. I need to check if there is a match and return the start and end location of a match. (The regex was already compiled by qr//.)

The function might also receive a "global" flag and then I need to return the (start,end) pairs of all the matches.

I cannot change the regex, not even add () around it as the user might use () and \1. Maybe I can use (?:).

Example: given "ababab" and the regex qr/ab/, in the global case I need to get back 3 pairs of (start, end).

Edit
Report

1 Answer

9

The pos function gives you the position of the match. If you put your regex in parentheses you can get the length (and thus the end) using length $1. Like this

sub match_positions {
    my ($regex, $string) = @_;
    return if not $string =~ /($regex)/;
    return (pos($string) - length $1, pos($string));
}
sub all_match_positions {
    my ($regex, $string) = @_;
    my @ret;
    while ($string =~ /($regex)/g) {
        push @ret, [pos($string) - length $1, pos($string)];
    }
    return @ret
}
answered 2008-09-17T20:38:53.420

Your Answer