First, don't use non-ASCII characters in your code unless you absolutely must have them there (e.g. as a value to be assigned to a variable). As pointed out above, using non-ASCII "smart quotes" to delimit literal strings in your code is an error.

Next, if you want to use $1 ($2, etc) after doing a regex match, you have to put parens into the regex to capture some part(s) of what is being matched.

Apart from those two points, there's not much that needs to be added to your code:

#!/usr/bin/perl use warnings; use strict; use diagnostics; my $Dna1 = "AACAGCACGGCAACGCTGTGCCTTGGGCACCATGCAGTACCAAACGGAACGATAGTGA +AAACAATCACGA\n"; while ($Dna1 =~ /(C[AG]G)/g) { my $endposition = pos($Dna1) + 1; print "Pattern C[AG]G matched $1 ending at $endposition\n"; }
When I run that, I get:
Pattern C[AG]G matched CAG ending at 6 Pattern C[AG]G matched CGG ending at 11 Pattern C[AG]G matched CAG ending at 38 Pattern C[AG]G matched CGG ending at 48
Those offset values (6, 11, 38, 48) represent the position of the next character after the 3-letter match (where the first character of the string is at position 1). That is, "6" points to the "C" that follows the first "CAG", "11" points to the "C" that follows the next "CGG", and so on.

(updated to fix a typo)


In reply to Re: Regex matching and position by graff
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.