in reply to Re: Re: Re: Re: Another regexp question
in thread Another regexp question

The regex "or" (Alternation, it's called) has fairly low precedence. That means that the ^ binds more closely than the |. The result is that you've got this going on:

m/ ^bing | bong | bang\d\d /x;

I used an "extended regular expression" so that I could group each subexpression (each alternate) on its own line. If you want the ^ to bind to all three, and the \d\d to bind to all three, you must use parenthesis to constrain the alternation. And if you aren't trying to capture, use non-capturing parens:

m/^b(?:i|o|a)ng\d\d/;

(Note: I factored out everything that is common to all three alternates. That step is unnecessary. You could use (?:bing|bong|bang) too.)

Alternation may be the best route to follow. But sometimes when you see it factored down as the previous example, you might suddenly realize, hey, I can do this with a character class too:

m/^b[ioa]ng\d\d/;


Dave


"If I had my life to live over again, I'd be a plumber." -- Albert Einstein

Replies are listed 'Best First'.
Re: Re: Re: Re: Re: Re: Another regexp question
by wolis (Scribe) on Nov 24, 2003 at 02:54 UTC
    Thankyou,

    you explained that so very clearly!

    I find the Perl pod fun and useful and a great read but its little things like "which binds more strongly ^ or |?" that I seem to only find out from useful people in PerlMonks.

    ___ /\__\ "What is the world coming to?" \/__/ www.wolispace.com