I've often found excellent solutions on this site so I'm hoping I can get some help with this one.
I have a pattern and a string. I'd like to search the string for the pattern and where it matches return the string that matches and the start and end position in the string of the match. If there are multiple matches I'd like to return this data for all the matches.
I think I'm on to something with the following but I'm not quite there. Any suggestions would be very much appreciated.
Cheers, Richard#!/usr/bin/perl use strict; my $string = "CATINTHEHATWITHABAT"; my $regex = '\wAT'; my @matches = (); foreach my $match ($string =~ /($regex)/gi){ my $length = length($&); my $pos = length($`); my $start = $pos + 1; my $end = $pos + $length; my $hitpos = "$start-$end"; push @matches, "$match found at $hitpos "; } print "$_\n" foreach @matches;
In reply to Match, Capture and get position of multiple patterns in the same string by richardwfrancis
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |