递归提取字符串中(嵌套)括号的内容 [英] Recursively extract contents of (nested) parentheses in string
问题描述
我正在尝试编写一个函数,以将括号中包含的单词提取到它们自己的数组中,以递归地解决嵌套括号的问题.
I'm trying to write a function that extracts the words contained in parentheses into their own array, recursively to account for nested parentheses.
因此,对于(((a b)ugh(one two))pi"",我希望将其转换为以下结构:
So for "((a b) ugh (one two)) pi", i'd like that to translate to the following structure:
[
[
[
"a",
"b"
],
"ugh",
[
"1",
"2"
],
]
"pi"
]
为此,我编写了以下函数:
To that end, I've written the following function:
function shitshow(hell) {
var ssparts = [];
var done = false;
for (i in hell) {
let part = hell[i];
switch(part) {
case "(":
ssparts.push(shitshow(hell.slice(i+1)));
break;
case ")":
done = true;
break;
default:
ssparts.push(part);
}
if (done) break;
}
return ssparts;
}
console.log(shitshow("((developer or engineer) or (nurse or doctor)) and manager"));
它不起作用.它为我返回的数组(我正在节点4上对其进行测试):
It doesn't work. The array it returns for me (I'm testing this on Node 4):
[
"",
[
"doctor"
],
[],
"developer",
"or",
"engineer"
]
曾为此奋斗了一段时间.有什么想法吗?
Been wrestling with this for a while. Any ideas?
如下面的@Oriol在这篇文章的评论中所述,我的发布代码不会产生我的发布输出.这是因为我忘了提及/在RegEx中将初始字符串包含在单词和非字母数字符号的数组中.为此事道歉.因为@Oriol已经发布了有效的解决方案,所以我包含此通知,而不是更新我的代码,以便他发布的解决方案可以正常使用.
As @Oriol mentioned below in this post's comments, my posted code does not produce my posted output. This is because I forgot to mention/include where I RegEx'd the initial string into an array of words and non-alphanumeric symbols. Sorry about this. Because @Oriol has already posted a working solution, I am including this notice instead of updating my code, so that his posted solution can stand.
推荐答案
我通常会执行以下操作.
I usually do something like the following.
外部函数将字符串作为参数接收,并声明用于对其进行迭代的外部变量.
An outer function receives the string as argument and declares outer variables used to iterate it.
这项工作是在递归内部函数中完成的,该函数会迭代直到)
.
The work is done in a recursive inner function which iterates until )
.
这样,我创建的所有新字符串都包含在返回的数组中.不会做无用的工作.
This way all new strings I create are included in the returned array. No useless work is done.
function shitshow(str) {
var i = 0;
function main() {
var arr = [];
var startIndex = i;
function addWord() {
if (i-1 > startIndex) {
arr.push(str.slice(startIndex, i-1));
}
}
while (i < str.length) {
switch(str[i++]) {
case " ":
addWord();
startIndex = i;
continue;
case "(":
arr.push(main());
startIndex = i;
continue;
case ")":
addWord();
return arr;
}
}
addWord();
return arr;
}
return main();
}
console.log(shitshow("((developer or engineer ) or (nurse or doctor)) and manager"));
div.as-console-wrapper { max-height: 100%; }
这篇关于递归提取字符串中(嵌套)括号的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!