in reply to validating string length with a regular expression

Test your code with this string (has a foo and is less than 50 chars so should match):

$_ = "foo\n Oops"; print /^(?=.{0,50}$).*foo/i ? "Matches!" : $_;

This fixes your regex:

/(?=^.{0,50}\z).*foo/si

\z only matches the end of the string (unlike $ which will match an embedded \n) and /s lets . match everything, including \n. Strictly you don't need the \z in this context and could leave the $ but it is good to know the difference. As you want to match foo it is more efficient to move the ^ .... \z into the lookahead which removes the need for the .* Death to dot star! Oops, updated per jehuni's comment below

This is a really silly way to do it that fulfils your criteria of being a single regex :-)

$str =~ s/(foo)/&do_stuff($str) if length $1 < 50; $1/e;

cheers

tachyon

s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

Replies are listed 'Best First'.
Re: validating string length with a regular expression
by jehuni (Pilgrim) on Mar 18, 2002 at 13:13 UTC

    Even though I don't expect to come across newline characters, your suggestion of using \z and /s is a good one. I definitely only want strings of 50 characters or less -- no matter what characters they are -- to match.

    Unfortunately, I don't see a way around using the dreaded .* before the actual pattern I'm looking for. Otherwise it will only match when the pattern occurs at the beginning of the string, since (?=^.{0,50}\z) is a zero-width assertion that's anchored to the start of the string. My original version had the ^ anchor inside the lookahead, like yours, but since it seemed that I had to use .* in either case, I decided to move it outside of the lookahead. However, it's probably clearer to leave it inside.

    Also, to clarify my question further, I actually need a matching regex and not a substitution regex. Maybe this is more like golf than I originally realized ...

    -jehuni

      Point taken about the anchoring. Insufficient testing with unusual edge case acknowledged :o)

      cheers

      tachyon

      s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print