替换嵌套括号中的内容 [英] Replace content present in the nested brackets

查看:62
本文介绍了替换嵌套括号中的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

输入= ABCDEF ((3) abcdef),GHIJKLMN ((4)(5) Value),OPQRSTUVW((4(5)) Value (3))

预期输出= ABCDEF,GHIJKLMN,OPQRSTUVW

到目前为止已经尝试过

Output = Input.replace(/ *\([^)]*\)*/g, "");

推荐答案

在这里使用正则表达式可能无法正常工作或缩放,因为您希望在输入字符串中加上 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);

这篇关于替换嵌套括号中的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆