in reply to newline in pattern matching

I think if you posted a little bit of code it would be easier to see what exactly you might be going on. As the /s not working could be attributed to a couple of things. To specify one: Is the variable you are matching the pattern against contain the whole of what you are trying to match, or are you doing a line by line comparison?

The /s modifier mainly allows the . char in the regex to also capture newlines whereas it otherwise would not.

-enlil

Replies are listed 'Best First'.
Re: Re: newline in pattern matching
by Anonymous Monk on Nov 15, 2002 at 17:41 UTC
    The latest version of coding I've been trying to use is:

    (/dist:(.+)$/ms)

    This works for all but the case where "dist:" and the number are on different lines.
      This code seems to do what you're looking for:
      #!/usr/bin/perl use strict; use warnings; my @data = ( "dist: 45 km;", "dist: 45\nkm;", "dist:\n45 km;" ); foreach my $chunk( @data ){ my( $distance ) = $chunk =~ /dist:.*?(\d+).*?km;/s; print STDOUT "$distance\n"; }

      Here's a breakdown of the regexp:
      /dist: # match 'dist:' .*? # match anything (including newlines), but only until th +e next part of the pattern starts to match (\d+) # match 1 or more digits, and put these into $1 .*? # same as before km; # match 'km;' (not needed unless you want to match a num +ber of these in one string) /s # treat the whole line as a single string


      Wonko's code works pretty much the same way. I think part of your problem may be that you appended "/ms" to your pattern. 'm' makes the regexp treat the string as multiple lines, and 's' makes the regexp treat the string as a single line, which is what you want it to do in this case. I don't know how those opposing options interact, but that may have caused some of your difficulty.

      One other option is to run $chunk =~ s/\n/ /; over each chunk. That will take all of the newlines out of each, so that all of the strings you gave as examples will evaluate to the same string. That would make a regexp much easier to write.
      --
      Love justice; desire mercy.
      I believe your problem is the /m flag - you're telling perl to match '$' to end of lines in the middle of a string. Try removing it.

      -- Dan