in reply to Re: How do I match lines of UP TO 40 chars BUT NO MORE in a block of text?
in thread How do I match lines of UP TO 40 chars BUT NO MORE in a block of text?

Thanks! However this is not working for me! Here is my code:

$foo = "line1line1line1line1line1line1line1line1 line2line2line2line2line2line2line2line2line2line2line2line2line2line2 +line2line2line2line2 line3line3line3line3line3line3line3line3"; if ($foo =~ /((?:^.{0,40})\n{1,4})/m) { print "$1: OK\n\n"; } else {print "$1: NOT OK\n\n";}

I get this as a result: line1line1line1line1line1line1line1line1
: OK

Which is not good, since line2 is greater than 40 chars.

thanks!

  • Comment on Re: Re: How do I match lines of UP TO 40 chars BUT NO MORE in a block of text?
  • Download Code

Replies are listed 'Best First'.
Re: Re: Re: How do I match lines of UP TO 40 chars BUT NO MORE in a block of text?
by sauoq (Abbot) on Sep 25, 2002 at 21:33 UTC

    Well, that's exactly what it should match. Your input matches your requirements. It has a block of text consisting of between 1 and 4 (1 in this case) lines of not more than 40 characters and an additional newline.

    Your requirements are poorly specified.

    Maybe, rather than see if your input matches such a block, you want to see if your input is such a block. If this is the case, your example input wouldn't work even if the second line had less than forty characters because your third line doesn't have a trailing newline.

    If that is what you are trying to do, try this:

    / ^ # Anchor to beginning of string. (?: # Group each line. .{0,40}\n # 0 to 40 characters followed by a newline. ){0,4} # 0 to 4 lines. $ # Anchor to end of string. /x; # /x for comments.
    -sauoq
    "My two cents aren't worth a dime.";
    
      WOW SAROQ! I think that finally did it! Thanks for all your help in this. As far as requests go, it is tough explaining things, and I know you gurus are excellent at responding quickly, that I get impatient. Sorry, learnt my lesson here.

      Anyway, my boss is going to test it, and lets hope it goes well for her.

      One quick question, I dont understand what the ?: at the beginning of the regex does. I took the comments out. What's the diff between these:

      1. ($foo =~ /^(?:.{0,40}\n){0,4}$/ 2. ($foo =~ /^(.{0,40}\n){0,4}$/ # note no ?:

      CHEERS MATE!
      Robert

        Without the ?: the parens will capture the match into $1. You probably don't need to capture. Presumably, not capturing will give you slightly better performance, though it probably wouldn't be noticeable unless you were doing a whole lot of matching.

        Glad I could help.

        -sauoq
        "My two cents aren't worth a dime.";