Thursday, January 27, 2011

Regular Expression Library to replace a repetition pattern

"test.txt" file has the following content
username@host.com
http://www.host.com


open FILEHANDLE,'test.txt' or die $!;
undef $/;
$string = <FILEHANDLE>;
print $string;


$HostNameRegex = qr/[-a-z0-9]+(\.[-a-z0-9]+)*\.(com|edu|info)/i;
$string =~ s{
\b
(
\w[-.\w]*
\@
$HostNameRegex
)
\b
}
{
<a href="mailto:$1">$1</a>
}gix;
$string =~ s{
\b
(
https?://$HostNameRegex\b
(
/[-a-z0-9_:!@?=+.*'%\$]*
(?<![.,?])
)?
)
}
{
<a href="$1">$1</a>
}gix;
The results: 
<a href="mailto:username@host.com">username@host.com</a>
<a href="http:..www.host.com">http:..www.host.com</a>

No comments:

Post a Comment