use strict;
my $str = '; Comment above the section
Key0=Value0
[Section 1]
Key=Value
[EmptySection]
Dummy text
;Commented Key=Value
;The following empty lines are ignored
;
#
[ Section 2 ]#Comment after [section];
Key 1 = Value 1
Key2 = Value 2 and [text in square brackets]
EmptyKey=
[];Noname section ignored
[ Section2 ] Dummy text after section
Key3 =Value 3 (symbols [;] are included)
#Key4 = Value 4 has been commented
Dummy text before section [ Sectionnum3 ]
Key 5 = Value 5
Key6 =Value6 ';
my $regex = qr/(?=\S)(?<text>(?<comment>(?<open>[#;]+)(?:[^\S\r\n]*)(?<value>.+))|(?<section>(?<open>\[)(?:\s*)(?<value>[^\]]*\S+)(?:[^\S\r\n]*)(?<close>\]))|(?<entry>(?<key>[^=\r\n\[\]]*\S)(?:[^\S\r\n]*)(?<delimiter>:|=)(?:[^\S\r\n]*)(?<value>[^#;\r\n]*))|(?<undefined>.+))(?<=\S)|(?<linebreaker>\r\n|\n)|(?<whitespace>[^\S\r\n]+)/ip;
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