且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

替换嵌套括号中的内容

更新时间:2022-12-28 15:56:39

在这里使用正则表达式可能无法正常工作或缩放,因为您希望在输入字符串中加上 nested 括号.当输入具有已知且固定的结构时,正则表达式可以很好地工作.相反,我建议您使用 parser 进行处理.在下面的代码中,我遍历输入字符串,一次只输入一个字符,然后使用计数器来跟踪有多少个开放括号.如果我们在括号内,则不记录这些字符.最后,我还做了一个简单的替换来删除空格,这是您的输出所暗示的又一个步骤,但是您从未明确提及.

Using a regex here probably won't work, or scale, because you expect nested parentheses in your input string. Regex works well when there is a known and fixed structure to the input. Instead, I would recommend that you approach this using a parser. In the code below, I iterate over the input string, one character at at time, and I use a counter to keep track of how many open parentheses there are. If we are inside a parenthesis term, then we don't record those characters. I also have one simple replacement at the end to remove whitespace, which is an additional step which your output implies, but you never explicitly mentioned.

var pCount = 0;
var Input = "ABCDEF ((3) abcdef),GHIJKLMN ((4)(5) Value),OPQRSTUVW((4(5)) Value (3))";
var Output = "";
for (var i=0; i < Input.length; i++) {
    if (Input[i] === '(') {
        pCount++;
    }
    else if (Input[i] === ')') {
        pCount--;
    }
    else if (pCount == 0) {
        Output += Input[i];
    }
}

Output = Output.replace(/ /g,'');
console.log(Output);