const regex = new RegExp('(?=\\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]+)', 'ig')
const 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 `;
// Reset `lastIndex` if this regex is defined globally
// regex.lastIndex = 0;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
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 JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions