This does what I want
my $line = q{one <two>}; $line =~ / ([^<]+) (?: < (two|three) > )? /x; print $1, $2;
one two
The <two> is optional and that works too. But I need
my $line = q{one <four>};
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.

Is this something that a look around assertion could handle? I've yet to conquer the blighters :-(

It will be used like

while ($line =~ /pattern/g){ # do something with $1 and $2 }
and a typical string
one [link|file.html] two [email|me@home.com] three [not a link]
What I have at the moment is fine but I'm not picking up three [not a link] in $1

while ( $line =~ / ( [^\[]* ) (?: \[ ( (?:link|email|pdf) [^\]]* ) \] )? /xg ) { my $txt = $1; my $link = $2; if ($link){ my ($type, $address, $txt) = split(/\|/, $link); # more stuff } }
tia

In reply to Regex: Optional/alternative catpures by wfsp

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.