CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Regular Expressions:
Greedy expression doesn't work like I expect

 



bobt_1234
New User

Jan 31, 2013, 3:24 PM

Post #1 of 4 (11771 views)
Greedy expression doesn't work like I expect Can't Post

Why doesn't this regular expression work like I expect?


Code
my $line = "/document/trial_date" 

my ($tag) = $line =~ /\/(.+?)$/;
print "$tag\n";


The output is "document/trial_date".
I expect to see "trial_date".

Doesn't the question mark do a "greedy" search? It should return everything from the last slash to the end of the string, I think.


wickedxter
User

Jan 31, 2013, 6:18 PM

Post #2 of 4 (11768 views)
Re: [bobt_1234] Greedy expression doesn't work like I expect [In reply to] Can't Post


Code
my $line = "/document/trial_date"; 

$line =~ /.+\/(.+)$/;

print $1;


this worked for me.. regex's are greedy


(This post was edited by wickedxter on Jan 31, 2013, 6:22 PM)


rovf
Veteran

Feb 1, 2013, 1:24 AM

Post #3 of 4 (11764 views)
Re: [bobt_1234] Greedy expression doesn't work like I expect [In reply to] Can't Post


Quote
Doesn't the question mark do a "greedy" search?


No, it's the opposite. By default, * and + are greedy, and the ? makes them non-greedy.

Reason is that we want to have greediness more frequently than non-greediness.


BillKSmith
Veteran

Feb 1, 2013, 5:46 AM

Post #4 of 4 (11752 views)
Re: [bobt_1234] Greedy expression doesn't work like I expect [In reply to] Can't Post

You question mark only makes the plus sign non-greedy. Other parts of your regex specify a match from the first slash to the end of the string. There is only one way to do this. Greediness does not make any difference in this case.

To match everything after the last slash, match all the non-slash characters at the end of the string.

Code
my ($tag) = $line =~ /\/([^/]+)$/;


This code finds the first slash that has only non-slashes after it (i.e. the last one). The parenthesis return those non-slash characters.
Good Luck,
Bill

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives