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:  <%-{-{-{-<


In reply to Re: Regex matching and position by AnomalousMonk
in thread Regex matching and position by PerlKc

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.