Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Regex becomes greedy with /s

by pingo (Hermit)
on Feb 26, 2010 at 09:58 UTC ( #825481=perlquestion: print w/replies, xml ) Need Help??

pingo has asked for the wisdom of the Perl Monks concerning the following question:

Dear monks, I have stumbled across an unexpected regex behaviour that I hope someone can explain. More specifically, this is the code:
$text = "<a href='http://www.example.com/'>Example 1</a>\n<a href='htt +p://www.example.net/' target='_blank'>Example 2</a>"; my ($a) = $text =~ /<a href='(.+?)' target='_blank'>/s; print "$a\n";
And this is the output:
http://www.example.com/'>Example 1</a> <a href='http://www.example.net/
I would have expected this, though:
http://www.example.net/
It is not much of a problem as such, as I can always change .+? to [^']+ or remove the /s. What I find a bit odd is that the /s makes the .+? greedy, despite the +?. Could someone please enlighten me?

Replies are listed 'Best First'.
Re: Regex becomes greedy with /s
by Corion (Pope) on Feb 26, 2010 at 10:02 UTC
      Ah... I think I understand.

      And this is just a throwaway script I am working on (at least I am fairly sure it is ;-)). If it was something more permanent, I'd certainly use one of the modules you mention.

        Another argument for TheDamian's PBP regex recommendation that a standard set of regex modifiers be used, even in 'throwaway' scripts. E.g.,
            m{pattern}xms

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://825481]
Approved by marto
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (2)
As of 2020-12-05 09:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    How often do you use taint mode?





    Results (63 votes). Check out past polls.

    Notices?