Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Find and extract substring(s) within larger string.

by 2teez (Priest)
on Oct 21, 2013 at 06:33 UTC ( #1059071=note: print w/ replies, xml ) Need Help??


in reply to Find and extract substring(s) within larger string.

Hi Anonymous Monk,
I am also considering capturing the beginning and ending index of each match (reading left to right)
You can also do like so, using while loop and index function:

use warnings; use strict; my $dna = 'xxxxxxpecbcbccrlxxxxxxpeeeerlxxxxxplxxxxxPeRLxxxx'; my $re = qr/p.*?l/i; while ( $dna =~ m[($re)]g ) { my $beg = index( $dna, $1 ); my $len = length($1); print join " " => $1, $beg, $beg + ($len -1), $/; # updated }
which produces..
pecbcbccrl 6 15 peeeerl 22 28 pl 34 35 PeRL 41 44
#Update: Correction of length of each string longer by one, as rightly pointed out by hdb

If you tell me, I'll forget.
If you show me, I'll remember.
if you involve me, I'll understand.
--- Author unknown to me


Comment on Re: Find and extract substring(s) within larger string.
Select or Download Code
Re^2: Find and extract substring(s) within larger string.
by hdb (Prior) on Oct 21, 2013 at 07:29 UTC

    Perl provides the $- and $+ @- and @+ arrays for this purpose (thanks to kcott pointing out that arrays have the @ sigil...):

    use warnings; use strict; # 1 2 3 4 # 0123456789012345678901234567890123456789012345678 my $dna = 'xxxxxxpecbcbccrlxxxxxxpeeeerlxxxxxplxxxxxPeRLxxxx'; my $re = qr/p.*?l/i; while ( $dna =~ m[($re)]g ) { print join " " => $1, $-[0], $+[0]-1, $/; }

    A correction of -1 is required, otherwise the matches are too long by one as in your code above.

      Hi hdb,
      A correction of -1 is required, otherwise the matches are too long by one as in your code above.
      You are right... my bad!

      If you tell me, I'll forget.
      If you show me, I'll remember.
      if you involve me, I'll understand.
      --- Author unknown to me

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (13)
As of 2014-09-16 13:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (19 votes), past polls