I need the Perl regex to parse plain text input and convert all links to valid HTML HREF links. I've tried 10 different versions I found on the web but none of them seen to work correctly. I also tested other solutions posted on StackOverflow, none of which seem to work. The correct solution should be able to find any URL in the plain text input and convert it to:
<a href="$1">$1</a>
Some cases other regular expressions I tried didn't handle correctly include:
- URLs at the end of a line which are followed by returns
- URLs that included question marks
- URLs that start with 'https'
I'm hoping that another Perl guy out there will already have a regular expression they are using for this that they can share. Thanks in advance for your help!
Besides
URI::Find
, also checkout the big regular expression database:Regexp::Common
, there is a Regexp::Common::URI module that gives you something as easy as:If you want different pieces (hostname, query parameters etc) in that uri, see the doc of Regexp::Common::URI::http for what's captured in the
$RE{URI}
regular expression.When I tried URI::Find::Schemeless with the following text:
it messed up
http://example.org/(9.3)
. So, I came up with the following with the help of Regexp::Common:This worked for the input shown. Of course, life is never that easy as you can see by trying
(http://example.org/(9.3))
.Here I have posted the sample code using how to extract the urls. Here it will take the lines from the stdin. And it will check whether the input line contains valid URL format. And it will give you the URL
Sample output I am getting is as follows
You want URI::Find. Once you extract the links, you should be able to handle the rest of the problem just fine.
This is answered in perlfaq9's answer to "How do I extract URLs?", by the way. There is a lot of good stuff in those perlfaq. :)