Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Perl > perl regular expressions return last matched occurence?

Reply
Thread Tools

perl regular expressions return last matched occurence?

 
 
Dustin D.
Guest
Posts: n/a
 
      08-26-2003
If I attempt to crop a string using regular expressions and the ()
operator for grouping, Perl always seems to return the last match.
For instance, if I have the following:

my $test = "a0\nb0\nc0\na1\nb1\nc1\n";
$test =~ s/.*(\w\d\n).*/$1/s;
print "$test";

The output would be:

c1

I don't understand why it's not a0? Any ideas?

Thanks,
Dustin
 
Reply With Quote
 
 
 
 
Rich
Guest
Posts: n/a
 
      08-28-2003
http://www.velocityreviews.com/forums/(E-Mail Removed) (Dustin D.) wrote in message news:<(E-Mail Removed). com>...
> If I attempt to crop a string using regular expressions and the ()
> operator for grouping, Perl always seems to return the last match.
> For instance, if I have the following:
>
> my $test = "a0\nb0\nc0\na1\nb1\nc1\n";
> $test =~ s/.*(\w\d\n).*/$1/s;
> print "$test";
>
> The output would be:
>
> c1
>
> I don't understand why it's not a0? Any ideas?
>
> Thanks,
> Dustin


It's all about greed.

Your .* is being greedy and going to the last group of word characters
which is c1. To stop it from being greedy add a ? after the first .*
and it should work the way you expect

Rich
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Replacing part of a matched regular expression using gsub Ben Ruby 4 03-25-2008 10:27 AM
Regular Expression - Show error if string is matched? monkeyjunkie ASP .Net Web Controls 1 11-11-2004 11:26 AM
Remembering part of last matched string Chandramohan Neelakantan Perl Misc 5 10-17-2003 08:13 AM
s/$pattern_to_match/$pattern_to_replace/ -- how can i use matched expressions? Mithras Perl Misc 1 09-14-2003 06:05 AM
Add custom regular expressions to the validation list of available expressions Jay Douglas ASP .Net 0 08-15-2003 10:19 PM



Advertisments