wfsp has asked for the wisdom of the Perl Monks concerning the following question:
my $line = q{one <two>}; $line =~ / ([^<]+) (?: < (two|three) > )? /x; print $1, $2;
The <two> is optional and that works too. But I needone two
to return one <four> in $1 and for $2 to be undef. Only capture to $2 if a pattern is matched otherwise capture the whole lot to $1.my $line = q{one <four>};
Is this something that a look around assertion could handle? I've yet to conquer the blighters :-(
It will be used like
and a typical stringwhile ($line =~ /pattern/g){ # do something with $1 and $2 }
What I have at the moment is fine but I'm not picking up three [not a link] in $1one [link|file.html] two [email|me@home.com] three [not a link]
tiawhile ( $line =~ / ( [^\[]* ) (?: \[ ( (?:link|email|pdf) [^\]]* ) \] )? /xg ) { my $txt = $1; my $link = $2; if ($link){ my ($type, $address, $txt) = split(/\|/, $link); # more stuff } }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Regex: Optional/alternative catpures (two)
by tye (Sage) on May 23, 2009 at 16:22 UTC |