const regex = new RegExp('^\\s*class\\s+
(?P<class>\\S+)[^{}]+(\\{
(?:[^{}]*|(?2))*
\\})', 'gm')
const str = `
<?php
// base class with member properties and methods
class Vegetable {
var \$edible;
var \$color;
function Vegetable(\$edible, \$color="green")
{
\$this->edible = \$edible;
\$this->color = \$color;
}
function is_edible()
{
return \$this->edible;
}
function what_color()
{
return \$this->color;
}
} // end of class Vegetable
// extends the base class
class Spinach extends Vegetable {
var \$cooked = false;
function __construct()
{
parent::__construct(true, "green");
}
function cook_it()
{
\$this->cooked = true;
}
function is_cooked()
{
return \$this->cooked;
}
} // end of class Spinach
?>
`;
// 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