我在嵌套括号中找到了许多匹配内容的正则表达式示例,但我要做的是匹配:
例如:
function someFunc() {
const a = 6;
if (a === 7) {
while (true) {
break;
}
}
}这应该会发现function someFunc+忽略任何直到第一个curly+then匹配大括号中所有内容的内容,包括任何嵌套的大括号。
我是regex的新手,所以我不能向你展示我做了什么,我一直在看Regex to get string between curly braces "{I want what's between the curly braces}",但它们都不合适。谢谢!
PS预期输出是函数中所有内容的捕获组(然后我可以替换它)。
发布于 2018-03-12 16:32:38
也许这个能帮上忙?
functionName\(.*{(.|\n)*}\n{2,}这将搜索一个名为functionName的函数,后面跟着一个括号,并得到所有内容,直到它找到一个结束的卷曲括号,然后是两个或多个换行符。
下面是一个测试它的Regex101。
发布于 2018-03-12 16:38:34
我为此做了一个非常天真的函数(因为这是我所需要的,因为我知道这个函数的内容是什么):
function loader(content, functionName) {
// Find function
const indexOfFunc = content.indexOf(`function ${functionName}`);
if (indexOfFunc < 0) {
return content;
}
const openingBrace = content.indexOf('{', indexOfFunc);
// WARNING: We are assuming all braces in the function are balanced.
// This won't be the case if there are braces in strings or comments
// which aren't!
const startPos = openingBrace + 1;
let endPos = startPos;
let bracesToBalance = 1;
while (true) {
if (content[endPos] === '{') {
bracesToBalance++;
} else if (content[endPos] === '}') {
bracesToBalance--;
if (bracesToBalance === 0) break;
}
endPos++;
}
return content.slice(0, startPos) + content.slice(endPos);
};https://stackoverflow.com/questions/49239492
复制相似问题