Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks, I'm trying to use a regex to see the 2nd line of a text file. The text file looks like this: USB::0x05E6::0x2220::9010183::INSTR USB::0x0699::0x03A4::C032029::INSTR "USB" is the beginning of a line and "INSTR" is the end. There are 2 lines. My regex looks like this:
if ($line =~ m/USB\d*::0x[0-9a-fA-F::]+0x[0-9a-fA-F]+::[0-9a-fA-F]+INS +TR\s*(.+?)\s*USB\d*/) { print $line; } }
From what I gathered from another post this: "s*(.+?)\s*" should get me to the next line because *s in this context is line feed. Can anyone tell me where I went wrong here?

Replies are listed 'Best First'.
Re: regex multi-line
by AppleFritter (Vicar) on Sep 15, 2014 at 23:19 UTC

    If you're reading your file line by line, i.e. if $line only ever contains one line, then a regular expression can't help you. The easiest way to see the second line of the file is to read two lines and discard the first, e.g. by saying

    <$FILE>; my $line = <$FILE>;

    But there's probably a reason you want to use a regular expression instead of doing this, so - what are your constraints, and what are you trying to do?

Re: regex multi-line
by kennethk (Abbot) on Sep 15, 2014 at 23:30 UTC
    If you want to test more than one time at a time, then you need to store more than one line in memory. The two most straightforward approaches here would be to cache the previous line:
    my $last = ''; while (my $line = <$fh>) { if ( $last =~ m/USB\d*::0x[0-9a-fA-F::]+0x[0-9a-fA-F]+::[0-9a-f +A-F]+INSTR$/ and $line =~ m/USB\d*::0x[0-9a-fA-F::]+0x[0-9a-fA-F]+::[0-9a-f +A-F]+INSTR$/) { print "$last$line"; } $last = $line; }
    or slurp the whole file and then grab the chunk you are interested in:
    my $content = do{local $/;<$fh>}; while ($content =~ /((?:USB\d*::0x[0-9a-fA-F::]+0x[0-9a-fA-F]+::[0-9a- +fA-F]+INSTR\n){2})/g) { print $1; }

    I should mention that your posted regex is inconsistent with what I'm presuming your text looks like, so you should post your input file, wrapped in code tags so whitespace doesn't get mangled. You should also be aware that \s*(.+?)\s* will require at least 1 non-newline character in the text joining your two lines, since without the s modifer, . won't match a newline.


    #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

Re: regex multi-line
by Laurent_R (Canon) on Sep 16, 2014 at 06:20 UTC
    From what I gathered from another post this: "s*(.+?)\s*" should get me to the next line because *s in this context is line feed.

    Do you mean s* or *s? In both cases, I wonder where you've picked up this idea...

Re: regex multi-line
by Anonymous Monk on Sep 15, 2014 at 22:32 UTC
    $line only has one line?
      $line only has one line, correct.
        So how would that regex get you to the second line if $line only has one line?