Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re^3: Extract a pattern from a string

by ambrus (Abbot)
on Jun 10, 2012 at 22:14 UTC ( #975484=note: print w/ replies, xml ) Need Help??


in reply to Re^2: Extract a pattern from a string
in thread Extract a pattern from a string

Beware with such a use of

index</i>, it is incorrect for it won't give you the offset you want i +f the substring appears more than once in the input. Eg. <c> $ perl -E 'my $s="ME170-5/2/10-ME172-5/2/10-ME4028"; while ($s=~m|(\d{ +1,2}/\d{1,2}/\d{1,2})|g){++$x;say "$x Found $1:" . (index($s,$1)+1)}' 1 Found 5/2/10:7 2 Found 5/2/10:7 $ perl -E 'my $s="ME170-5/2/10-ME172-5/2/1-ME4028"; while ($s=~m|(\d{1 +,2}/\d{1,2}/\d{1,2})|g){++$x;say "$x Found $1:" . (index($s,$1)+1)}' 1 Found 5/2/10:7 2 Found 5/2/1:7 $

Instead, if you really want to know the offsets, then use either the pos or the @- match variable to find where the regular expression has matched:

$ perl -E 'my $s="ME170-5/2/10-ME172-5/2/10-ME4028"; while ($s=~m|(\d{ +1,2}/\d{1,2}/\d{1,2})|g){++$x;say "$x Found $1:" . $-[1]}' 1 Found 5/2/10:6 2 Found 5/2/10:19 $ perl -E 'my $s="ME170-5/2/10-ME172-5/2/1-ME4028"; while ($s=~m|(\d{1 +,2}/\d{1,2}/\d{1,2})|g){++$x;say "$x Found $1:" . $-[1]}' 1 Found 5/2/10:6 2 Found 5/2/1:19 $

However, maybe you don't want to know the positions at all, but instead match the port numbers and dates with a single regular expression that has two captures.

Also, those newlines and plus signs inside the braces are just a mistake you made when pasting here, right?


Comment on Re^3: Extract a pattern from a string
Select or Download Code
Re^4: Extract a pattern from a string
by avim1968 (Novice) on Jun 11, 2012 at 04:03 UTC
    Hi
    thank you for the warning, I just hit that problem during the run.
    when i got the same port number in a line.
    i'll modify my script again, with your input.
    thank you
    Avi
    p.s.
    all those newlines and plus signs inside the braces are not
    mine but were placed there after pasting the code.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (7)
As of 2014-07-26 15:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (178 votes), past polls