use strict;
my $str = 'http://example.com
https://www.example.com
http://example.com/path
https://www.example.com/path
http://example.com/path?query=1
https://www.example.com/path?query=1
http://example.com/path#fragment
https://www.example.com/path#fragment
http://example.com:8080
https://www.example.com:8080
http://subdomain.example.com
https://www.subdomain.example.com
http://subdomain.example.com/path
https://www.subdomain.example.com/path
http://subdomain.example.com/path?query=1
https://www.subdomain.example.com/path?query=1
http://subdomain.example.com/path#fragment
https://www.subdomain.example.com/path#fragment
http://subdomain.example.com:8080
https://www.subdomain.example.com:8080
http://example.org
https://www.example.org
http://example.org/path
https://www.example.org/path
http://example.org/path?query=1
https://www.example.org/path?query=1
http://example.org/path#fragment
https://www.example.org/path#fragment
http://example.org:8080
https://www.example.org:8080
http://subdomain.example.org
https://www.subdomain.example.org
http://subdomain.example.org/path
https://www.subdomain.example.org/path
http://subdomain.example.org/path?query=1
https://www.subdomain.example.org/path?query=1
http://subdomain.example.org/path#fragment
https://www.subdomain.example.org/path#fragment
http://subdomain.example.org:8080
https://www.subdomain.example.org:8080
http://example.net
https://www.example.net
http://example.net/path
https://www.example.net/path
http://example.net/path?query=1
https://www.example.net/path?query=1
http://example.net/path#fragment
https://www.example.net/path#fragment
http://example.net:8080
https://www.example.net:8080';
my $regex = qr/^(?P<scheme>http(?:s)?:\/\/)?(?P<www>www\d?\.)?(?P<domain>\b(?!www\d?\.)[a-z\d\-]+(?:\.[a-z\d\-]{2,})+)(?P<port>:\d{1,5})?(?P<path>\/(?:[-a-zA-Z0-9._~!$&\'()*+,;=:@]|%[0-9a-fA-F]{2})*)*(?P<query_fragm>[?#&][\/\_\-\&\%\?\#\+\=\.:a-zA-Z\d]*)*$/mp;
if ( $str =~ /$regex/g ) {
print "Whole match is ${^MATCH} and its start/end positions can be obtained via \$-[0] and \$+[0]\n";
# print "Capture Group 1 is $1 and its start/end positions can be obtained via \$-[1] and \$+[1]\n";
# print "Capture Group 2 is $2 ... and so on\n";
}
# ${^POSTMATCH} and ${^PREMATCH} are also available with the use of '/p'
# Named capture groups can be called via $+{name}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Perl, please visit: http://perldoc.perl.org/perlre.html