Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re^3: Match variables : Beginner in perl -- webperl

by jbodoni (Monk)
on Jan 03, 2019 at 11:26 UTC ( [id://1227964]=note: print w/replies, xml ) Need Help??


in reply to Re^2: Match variables : Beginner in perl -- webperl
in thread Match variables : Beginner in perl

Regex greediness: If you want to find the string one two three in "one two three" "four five six", your first thought might be to use m/"(.*)"/

This will return one two three" "four five six because the regex will match as many characters as it can. It will match until the last " it finds.

Instead, use m/"(.*?)"/, which will stop matching as soon as it can.

  • Comment on Re^3: Match variables : Beginner in perl -- webperl

Replies are listed 'Best First'.
Re^4: Match variables : Beginner in perl -- webperl
by dsheroh (Monsignor) on Jan 03, 2019 at 11:40 UTC
    Instead, use m/"(.*?)"/, which will stop matching as soon as it can.
    Or, better (at least when you're going up to a single-character terminator), be more explicit about what you actually want by using a negated character class: m/"([^"]*)"/

    If you want to match anything except a double-quote, tell Perl to match "anything except a double-quote" ([^"]), not "the shortest possible set of anything at all that happens to have a double-quote after it" (.*?").

    Also, more pragmatically, if there's more to your regex after this part, then you could get cases where (.*?)" will still contain double-quotes in the match if that's needed to make the "more after this part" work. Because it's more explicit about not matching double-quotes, ([^"]*) will never have them in the match.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1227964]
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