gpt4 book ai didi

javascript - 排除 if 之间,但更复杂

转载 作者:行者123 更新时间:2023-12-01 00:34:55 26 4
gpt4 key购买 nike

所以,我正在尝试制作正则表达式,它将解析存储在对象中的所有全局函数声明,例如,像这样 const a = () => {}

我做了这样的事情:

/(?:const|let|var)\s*([A-z0-9]+)?\s*=\s(函数\s*\(([^)(]+) |\((?:[^)(]+|\([^)(]*\))*\))*\)|\(([^)(]+|\((?:[^) (]+|\([^)(]*\))*\))*\)\s*\=\>)\s*\{((?:[^}{]+|\{[^) }{]*\}|[^}]|\}(\"|\'|\ ))*)*\}/g

它工作正常,但我遇到了内部声明问题 ( link )

如果链接不起作用:

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)

那么,有什么想法,如何排除内部函数声明吗?

我尝试过否定前瞻(?!),但我的实验没有给出所需的结果。

最佳答案

使用多行运算符并将您的lookbehind更改为 anchor ,如下所示

/^(const|let|var)\s*([A-z0-9]+)?\s*=\s(function\s*\(([^)(]+|\((?:[^)(]+|\([^)(]*\))*\))*\)|\(([^)(]+|\((?:[^)(]+|\([^)(]*\))*\))*\)\s*\=\>)\s*\{((?:[^}{]+|\{[^}{]*\}|[^}]|\}(\"|\'|\`))*)*\}/gm

查看输出here

关于javascript - 排除 if 之间,但更复杂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58209341/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com