This is a good reason to use a /ex block to perform the magic.

local $/; my $data = <DATA>; $data =~ s{\[([^\[]*)\]} { my @bits = split '\|', $1; @bits= map{ s/^\s+|\s+$//g; $_}grep{ ! m/^\s*$/ } @bits; if ( @bits == 0 ) { # error handling just return original qq![$1]!; } else { # may want to auto add $bits[0] = "http://$bits[0]" unless $bits[0] =~ m/^(?:https?|ftp)/ or $bits[0] =~ m/[a-z][A-Z]|[A-Z][a-z]/; #camelCa +se if ( @bits == 1 ) { qq!<a href="$bits[0]">$bits[0]</a>!; } elsif ( @bits == 2 ) { qq!<a href="$bits[0]">$bits[1]</a>!; } elsif ( @bits == 3 ) { qq!<a href="$bits[0]" target="$bits[2]">$bits[1]</a>!; } } }gex; print $data; __DATA__ This is an error [] This is OK [www.perlmonks.org] This is OK [www1.test.com|test page1] This is OK [www2.test.com|test page2|new] This is errorish [www2.test.com|test page2|] This is errorish [ www2.test.com | test page2 | ] This is camelCase [ camelCase|Local Link in Blog | new ]

This allows you to handle errors gracefully (ie tolerate whitespace errors) and say add http:// to apparently external links and ignore for camelCase links (assuming this is for a blog) ie:

This is an error [] This is OK <a href="http://www.perlmonks.org">http://www.perlmonks.org +</a> This is OK <a href="http://www1.test.com">test page1</a> This is OK <a href="http://www2.test.com" target="new">test page2</a> This is errorish <a href="http://www2.test.com">test page2</a> This is errorish <a href="http://www2.test.com">test page2</a> This is camelCase <a href="camelCase" target="new">Local Link in Blog< +/a>

cheers

tachyon


In reply to Re: Link regex by tachyon
in thread Link regex by coldfingertips

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.