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

  Main Index MAIN
Search Posts SEARCH
Who's Online WHO'S
Log in LOG

Home: Perl Programming Help: Regular Expressions: Re: [TheBlackNoodle] Match largest or smallest?: Edit Log


Jun 26, 2008, 6:45 PM

Views: 15207
Re: [TheBlackNoodle] Match largest or smallest?

In Reply To

So I've organized a regex that uses alternation so that the longest match will come out first. That makes sense.

regex: [aeiou]+

Say I have the word "conscious" and I want to match the "scious" portion. When matched with the regex, it returns "iou", which is correct. However, I would also like to get the smallest possible match, which is just "i". The problem is that I can't change the original regex, but I can append to it.

Is there a good way to go about finding both the largest and smallest match?

What you have is not alternation, it is a character class, they are two different things. The smallest possible match is the first "o" in the string, not the first "i". The "+" quantifier means one or more so the first "o" matches that since it is a quantity of one. What I think you are loonking for is 2 or more: {2,} but if that is the case the smallest match is "io".

$foo = 'conscious'; 
$foo =~ /([aeiou]{2,}?)/;
print $1;

prints 'io' because the ? makes the match true for the shortest match (non-greedy matching). If you want to skip single vowels (ie: 'con') you have to change your regexp. Maybe this will work:

$foo = 'conscious'; 
$foo =~ /([aeiou])[aeiou]+/;
print $1;


(This post was edited by KevinR on Jun 26, 2008, 6:48 PM)

Edit Log:
Post edited by KevinR (Veteran) on Jun 26, 2008, 6:48 PM

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

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