in reply to Extract a pattern from a string

In his reply davido mentions the special arrays @- and @+ which store the start and end character indexes for various matched portions of the string being matched. However, most often those indexes are a means to an end and most often Perl provides better means. It's kind of hard for us to help you find those means however because you've not told us what you want to do. If you take a step back and describe the bigger picture we may be able to offer more help.

True laziness is hard work

Replies are listed 'Best First'.
Re^2: Extract a pattern from a string
by avim1968 (Acolyte) on Jun 10, 2012 at 09:41 UTC

    Hi
    The BIG picture is very simple
    i have a list of strings like i showed
    ME170-5/2/8-ME172-2/2/6-ME4028
    ME172-2/1/2-ME196-1/1/3-ME4002
    i need to extract from each string the port numbers ie 5/2/8 or 2/2/6 etc..
    then according to an index of a number found in the string
    i need to select the port with the correct index number.
    for example with the strings above.
    string 1 = ME170-5/2/8-ME172-2/2/6-ME4028
    string 2 = ME172-2/1/2-ME196-1/1/3-ME4002
    if my search number is 172 then for
    string 1 i would get 2/2/6
    and for string 2 i would get 2/1/2
    thank you
    Avi

      After reading all the answers in this topic i have managed
      to create my Perl code to do just what i need
      Thank you ALL :-)
      Avi

      If knowing the position of the port number in the string is necessary in order to be able to work your way back to and extract the index number, there's a more direct way:

      >perl -wMstrict -le "my $dd = qr{ \d{1,2} }xms; ;; my %indices; for my $s ( 'ME170-5/2/8-ME172-2/2/6-ME4028-FOO172-222/2/666-BAR', 'ME172-2/1/2-ME196-1/1/33-ME4002-11/2/3-ME1-1/22/3-ME22', '1-1/2/3', 'ME-9/9/9-ME', ) { push @{ $indices{$1} }, $2 while $s =~ m{ (\d+) - ($dd (?: / $dd){2}) }xmsg; } ;; for my $i (sort { $a <=> $b } keys %indices) { printf qq{index '$i': port(s) '%s' \n}, join q{' '}, @{ $indices{$i} }; } " index '1': port(s) '1/22/3' '1/2/3' index '170': port(s) '5/2/8' index '172': port(s) '2/2/6' '2/1/2' index '196': port(s) '1/1/33' index '4002': port(s) '11/2/3'