http://qs321.pair.com?node_id=153444

Kozz has asked for the wisdom of the Perl Monks concerning the following question:

Most wise monks: I know that aspects of my questions have been touched on in various other nodes, but I've done my homework and node research, so please don't shred me to bits. I throw myself on the mercy of your monkship.

The book "Mastering Regular Expressions" is on my wishlist, but thus far I consider myself to be perhaps only an intermediate-skilled monk with regexes. My goal is to create a sub that would "hotlink" text containing http or mailto URIs. This has been done in another node, but not to the extent to which I'd like, and doesn't cover all cases. I've read up on perlman:perlre, Email::Valid as well, and saw the nightmare-ish super-long regex, which was far more complex than I was hoping for. The thing is that I don't really want/need to validate the domain and mx record for emails or whatever - just want to identify those things that LOOK LIKE URIs and hyperlink them accordingly. Perhaps there are other modules which could be used in conjunction with one another to identify potential URIs and deal with all the different formats/cases? See the code below.

#!/usr/bin/perl use strict; my $string = q{ An email address is foo-master@bar.com, but this http://foo@bar.com/ and this ftp://foo:baz@bar.com/ are not emails. }; my $desired_output = q{ An email address is <A HREF="mailto:foo-master@bar.com">foo-master@b +ar.com"</A>, but this <A HREF="http://foo@bar.com/">http://foo@bar.com/</A> and this <A HREF="ftp://foo:baz@bar.com/">ftp://foo:baz@bar.com/</A> are not emails. }; foreach($string){ # make http or ftp hyperlinks first s#((ht|f)tp://[\S]+)#<A HREF="$1">$1</A>#isg; # now make email addresses hyperlinks # but don't "email-ify" http or ftp URIs s#((?<!tp://)[a-z0-9\-\_\.]+\@[a-z0-9\-]+(\.[a-z0-9\-]+)+)#<A HRE +F="mailto:$&">$&</A>#isg; if( m#(?<!tp://)[a-z0-9\-\_\.]+\@[a-z0-9\-]+(\.[a-z0-9\-]+)+#isg) +{ print "Yes, it matches ($&).\n"; }else{ print "It does not match.\n"; } print; }
If you try the code, you'll see that the actual output of the above regex is
Yes, it matches (foo-master@bar.com). An email address is <A HREF="mailto:foo-master@bar.com">foo-master@b +ar.com</A>, but this <A HREF="http://f<A HREF="mailto:oo@bar.com">oo@bar.com</A>/">h +ttp://f<A HREF="mailto:oo@bar.com">oo@bar.com</A>/</A> and this <A HREF="ftp://foo:<A HREF="mailto:baz@bar.com">baz@bar.com</A> +/">ftp://foo:<A HREF="mailto:baz@bar.com">baz@bar.com</A>/</A> are not emails.
:-( I thought I could surely get this figured out with a moderately simple regex, but the test-cases I've used here have proved quite difficult. How close am I? Or am I going about it the wrong way, or can it not be done with these test cases? I thank you in advance for your consideration. --Kozz