use strict;
my $str = '';
my $regex = qr/(?(DEFINE)
(?P<ver>\d+(?:\.\d+)*(?![.\d]))
(?P<agent>Mozilla\/(?&ver))
(?P<os>(?&os_windows)|(?&os_linux)|(?&os_macintosh)|(?&os_ios))
(?P<os_windows>Windows[ ]\w+[ ](?&ver))
(?P<os_linux>Linux(?:[ ](?:i686|x86_64))?)
(?P<os_macintosh>Macintosh)
(?P<os_ios>(?:CPU[ ])?iPhone[ ]OS|CPU[ ]OS.*?like[ ]Mac[ ]OS[ ]X)
(?P<device>(?&device_ios)|(?&device_firefox)|(?&device_android))
(?P<device_ios>iPhone|iPad)
(?P<device_firefox>Mobile)
(?P<device_android>Android(?:[ ](?&ver))?)
(?P<browser>
(?:
(?&browser_ie)
| (?&browser_safari)
| (?&browser_chrome)
| (?&browser_chromium)
| (?&browser_firefox)
| (?&browser_version)
# | (?&browser_nexus)
| (?&browser_mobile)
| (?&browser_gsa)
| (?&browser_quicklook)
| (?&browser_opera)
)
[ \/]
(?: [A-Z\d]+\b(?!\.) | (?&ver) )
)
(?P<browser_safari>(?:Mobile[ ])?Safari)
(?P<browser_chrome>Chrome)
(?P<browser_chromium>\b\w+\b[ ]Chromium)
(?P<browser_firefox>Firefox)
(?P<browser_ie>MSIE)
(?P<browser_version>Version)
(?P<browser_nexus>Nexus[ ]\d+[ ]Build)
(?P<browser_mobile>Mobile)
(?P<browser_gsa>GSA)
(?P<browser_quicklook>QuickLook)
(?P<browser_opera>OPR)
)
^
(?:(?=.*?(?P<Agent>(?&agent))))
(?:(?=.*?(?P<OS>(?&os))))
(?:(?=.*?(?P<Device>(?&device))))?
(?:(?=.*?(?P<Browser>(?&browser)(?:[ ](?&browser))*)))?/mxp;
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