Reputation: 88
So, i'm trying to make regex, which would parse all global functions declarations, stored in objects, for example, like this const a = () => {}
I make something like this:
/(?:const|let|var)\s*([A-z0-9]+)?\s*=\s(function\s*\(([^)(]+|\((?:[^)(]+|\([^)(]*\))*\))*\)|\(([^)(]+|\((?:[^)(]+|\([^)(]*\))*\))*\)\s*\=\>)\s*\{((?:[^}{]+|\{[^}{]*\}|[^}]|\}(\"|\'|\
))*)*\}/g
It work fine, but I got a problem with inner declaration (link)
If link don't work:
const definedJsFunctionsAsObjectRegex = /(?:const|let|var)\s*([A-z0-9]+)?\s*=\s(function\s*\(([^)(]+|\((?:[^)(]+|\([^)(]*\))*\))*\)|\(([^)(]+|\((?:[^)(]+|\([^)(]*\))*\))*\)\s*\=\>)\s*\{((?:[^}{]+|\{[^}{]*\}|[^}]|\}(\"|\'|\`))*)*\}/g;
const str = `
let f = function(a,b) {
console.log(gdhfsgdfg);
}
const f2 = (a,b, d) => { blabla }
let f3 = function(){
fdgdhgf
}
function test() {
const inner = (t, b) => { im must be undetected}
const inner2 = function (a,b) {
im must be undetected too
}
}
// here checking for }"
function(fds) { obj = {} return "}" }
function r () { obj = {}; a = []; }
function a(){console.log('a')} function b(){console.log('b')}
`;
let matches = [...str.matchAll(definedJsFunctionsAsObjectRegex)];
console.log(matches)
So, any ideas, how to exclude inner functions declarations?
I'm tried negative lookahead (?!), but my experiments did not give the desired result.
Upvotes: 0
Views: 45
Reputation: 5204
Use the multiline operator and change your lookbehind to an anchor like so
/^(const|let|var)\s*([A-z0-9]+)?\s*=\s(function\s*\(([^)(]+|\((?:[^)(]+|\([^)(]*\))*\))*\)|\(([^)(]+|\((?:[^)(]+|\([^)(]*\))*\))*\)\s*\=\>)\s*\{((?:[^}{]+|\{[^}{]*\}|[^}]|\}(\"|\'|\`))*)*\}/gm
See the output here
Upvotes: 2