http://www.perlmonks.org?node_id=918984


in reply to Re: Determing if this regex matched
in thread Determing if this regex matched

Hey! I had no idea s/// returned anything. Also a more straightforward way to write the regex. Problem is, with the or, the second sub doesn't get executed if the first one matches, so there is still the trailing quote on examples 1 and 4. I suppose one could do
my @items = ('"Title Text Example"', 'Title Text Example', ' Title Tex +t Example ',' "Title Text Example"'); foreach my $title (@items) { my $changed = 0; if ($title =~ s/^[\s"]+//) { $changed=1; } if ($title =~ s/[\s"]+$//) { $changed=1; } if ($changed) { print "$title\n"; } }
But that doesn't seem very elegant.

Replies are listed 'Best First'.
Re^3: Determing if this regex matched
by ww (Archbishop) on Aug 06, 2011 at 20:06 UTC
    For the elegant method, try perlretut (and family), "Mastering Regular Expressions," Tutorials, perhaps.

    But -- IMO -- "elegant" is frequently overrated; the real question, I think, is "does it work, consistently?"

      Well good point.

      I still wonder why is $& always null in the original example.

        ... why is $& always null in the original example.

        I think the answer is that $ (in the original example) and \z (in the example below) match after the last character in the string: that's the 'position' of the end of the string. For instance, in the string 'xa' the 'a' can match and is replaced, but after this match the match position (as returned by pos) is just beyond the end of the string, where it can match once again with no 'a', no whitespace and \z — a zero-length match!

        >perl -wMstrict -le "my @strings = ('x', 'xa', 'x ', 'xa ',); ;; for my $s (@strings) { $s =~ s{ a? \s* \z } { print qq{\$& '$&' pos = }, pos($s); ''; }xmseg; print qq{\$s '$s' \n}; } " $& '' pos = 1 $s 'x' $& 'a' pos = 1 $& '' pos = 2 $s 'x' $& ' ' pos = 1 $& '' pos = 2 $s 'x' $& 'a ' pos = 1 $& '' pos = 3 $s 'x'

        Update: N.B.: The /g regex modifier does not act to 'reset' $&, $1, or other match variables.

Re^3: Determing if this regex matched
by merlyn (Sage) on Aug 06, 2011 at 20:12 UTC
    Too much work!
    my @items = ('"Title Text Example"', 'Title Text Example', ' Title Tex +t Example ',' "Title Text Example"'); foreach (@items) { if (s/^[\s"]+// or s/[\s"]+$//) { print "$_\n"; } }

    -- Randal L. Schwartz, Perl hacker

    The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119.

      That's what toolic had before editing the his post. Doesn't work because if the first element of the or evaluates true the second one doesn't get evaluated, so if there's a quote/space at the beginning, quotes/spaces get left at the end.