Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: Regex matching and position

by graff (Chancellor)
on Oct 21, 2015 at 01:42 UTC ( [id://1145504]=note: print w/replies, xml ) Need Help??


in reply to Regex matching and position

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)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1145504]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (3)
As of 2024-04-25 17:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found