in reply to Regex matching and position

A slightly different approach:

c:\@Work\Perl\monks>perl -wMstrict -le "my $Dna1 = qq{AACAGCACGGCAACGCTGTGCCTTGGGCACCATGCAGTACCAAACGGAACGATAG +TGAAAACAATCACGA\n}; ;; while ($Dna1 =~ /C[AG]G/g) { my ($start, $end, $len) = ($-[0], $+[0], $+[0]-$-[0]); print qq{pattern C[AG]G matched @ offsets $start thru $end, $len lo +ng}; } " pattern C[AG]G matched @ offsets 2 thru 5, 3 long pattern C[AG]G matched @ offsets 7 thru 10, 3 long pattern C[AG]G matched @ offsets 34 thru 37, 3 long pattern C[AG]G matched @ offsets 44 thru 47, 3 long
c:\@Work\Perl\monks>perl -wMstrict -le "my $Dna1 = qq{AACAGCACGGCAACGCTGTGCCTTGGGCACCATGCAGTACCAAACGGAACGATAG +TGAAAACAATCACGA\n}; ;; while ($Dna1 =~ /(C[AG]G)/g) { my $sub_seq = $1; my ($start, $end, $len) = ($-[1], $+[1], $+[1]-$-[1]); print qq{matched '$sub_seq' @ offsets $start thru $end, $len long}; } " matched 'CAG' @ offsets 2 thru 5, 3 long matched 'CGG' @ offsets 7 thru 10, 3 long matched 'CAG' @ offsets 34 thru 37, 3 long matched 'CGG' @ offsets 44 thru 47, 3 long
Note that once again, the ending offset is for the first character after the matched sub-sequence. Note also that this regex matches non-overlapping sub-sequences only. (A slightly different regex can match overlaps if you need this.) See the perlvar subsection "Variables related to regular expressions" for  @- @+ special regex array info.

Update: Reading the OP more closely, I see you want to capture and print the matched sub-sequence also. I have posted new code to do this using a capture group. Sorry for any confusion. (Update: Buried the evidence a bit deeper under some  <readmore> tags.)


Give a man a fish:  <%-{-{-{-<

Replies are listed 'Best First'.
Re^2: Regex matching and position
by Anonymous Monk on Jun 08, 2019 at 18:52 UTC
    you save my day. maybe this is not the right place, but I just wanted to thank all perlmonks. every time I had a hard problem with perl, I easily found a solution in perlmonks.org so thank you all.

      You're very welcome. We exist to serve. (You might also think about stopping by the Offering Plate.)


      Give a man a fish:  <%-{-{-{-<