Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: Determing if this regex matched

by toolic (Bishop)
on Aug 06, 2011 at 19:40 UTC ( [id://918980]=note: print w/replies, xml ) Need Help??


in reply to Determing if this regex matched

Use an "if" statement to check the return of s/// (returns the number of substitutions made; false otherwise):
use strict; use warnings; my @items = ('"Title Text Example1"', 'Title Text Example2', ' Title T +ext Example3 ',' "Title Text Example4"'); foreach my $title (@items) { my $match = 0; $match++ if $title =~ s/^[\s"]+//; $match++ if $title =~ s/[\s"]+$//; print "$title.\n" if $match; } __END__ Title Text Example1. Title Text Example3. Title Text Example4.
Updated to match both begin and end.

Replies are listed 'Best First'.
Re^2: Determing if this regex matched
by cormanaz (Deacon) on Aug 06, 2011 at 19:57 UTC
    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.
      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.

      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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://918980]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (4)
As of 2024-04-26 00:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found