Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

Re: regex question/mystery

by philcrow (Priest)
on Jan 17, 2006 at 18:37 UTC ( #523797=note: print w/replies, xml ) Need Help??

in reply to regex question/mystery

Update: the answer formerly here was wrong. Sorry.


Replies are listed 'Best First'.
Re^2: regex question/mystery
by davido (Cardinal) on Jan 17, 2006 at 18:58 UTC

    Your conclusion is wrong. Alternation has very low precedence, and binds loosely. In the following expression, alternation provides two alternatives, the complete expression on the left, or the complete expression on the right:


    The string matched by that RE must contain either "fast break" or "breakfast" (or both, but it wouldn't matter). In either case, 'break' is captured, but $& tells the rest of the story. Witness the following code:

    use strict; use warnings; my $string = "breakfast break"; if( $string =~ m/fast\s(break)|(break)fast/ ) { print "\$1 contains ", defined( $1 ) ? $1 : "undef", "\n"; print "\$2 contains ", defined( $2 ) ? $2 : "undef", "\n"; print "The portion of the string that matched was $&\n"; } __OUTPUT__ $1 contains undef $2 contains break The portion of the string that matched was breakfast

    The alternation is constrained on each side only be the / (the beginning and end of the RE, not by (break). That being the case, there is no need to have introduced additional parenthesis in the OP's regex. In fact, you have now changed the outcome of his RE in another way; to get at the data he intended to capture, he now must look at $2 or $4.


Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://523797]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (4)
As of 2022-05-17 11:37 GMT
Find Nodes?
    Voting Booth?
    Do you prefer to work remotely?

    Results (65 votes). Check out past polls.