const regex = /^\s*(Public|Private)?(?:\s*)(Function|Sub)(?:\s*)([a-zA-Z_]\w*)\s*(?:\()([^)]*)(?:\))(?:\sAs\s)?(\w*)?([\s\S]*?)^\s*(?:End Function|End Sub)/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('^\\s*(Public|Private)?(?:\\s*)(Function|Sub)(?:\\s*)([a-zA-Z_]\\w*)\\s*(?:\\()([^)]*)(?:\\))(?:\\sAs\\s)?(\\w*)?([\\s\\S]*?)^\\s*(?:End Function|End Sub)', 'gm')
const str = `Attribute VB_Name = "mdl_WbkInits"
Option Compare Database
Function InitWbk_004(byRef wbkRef As Object)
Dim wbk As wbk_004_InstoreBrief
Set wbk = New wbk_004_InstoreBrief
Call wbk.wbk_Init(wbkRef)
Set InitWbk_004 = wbk
End Function
Public Function InitWbk_003(ByRef wbkRef As Object) As Object
Dim wbk As wbk_003_3DCalculation
Set wbk = New wbk_003_3DCalculation
Call wbk.wbk_Init(wbkRef)
Set InitWbk_003 = wbk
End Function
`;
// 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