如何去掉不必要的括号? [英] How to remove unnecessary parenthesis?

查看:74
本文介绍了如何去掉不必要的括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

this 相同,但 JavaScript.举几个例子来说明我的目标:

Same as this but JavaScript. A few examples to illustrate my goal:

  • ((((foo))) => (foo)
  • ((foo)) => (foo)
  • (foo) => (foo)
  • (foo (bar)) => (foo (bar))
  • ((foo b)ar) => ((foo b)ar)
  • (((a)b(c))) => ((a)b(c))

我制作了一个正则表达式,它应该与我想要更改的那些匹配 /\({2,}[\s\S]*\){2,}/g 但我不能似乎不知道如何删除它们.

I have made a regex which should match the ones I want to change /\({2,}[\s\S]*\){2,}/g but I can't seem to figure out how to remove them.

有没有类似String.replace(/\({2,}[\s\S]*\){2,}/g, '(${rest})')?

推荐答案

与其纠结于正则表达式,我建议您尝试经典的标记化解析生成工作流程.想法是将字符串解析为数据结构(在本例中为嵌套数组),简化该结构并从中生成新字符串.

Instead of struggling with regexes I'd suggest you try the classic tokenize-parse-generate workflow. The idea is to parse a string into a data structure (in this case, nested arrays), simplify that structure and generate a new string from it.

示例:

function tokenize(str) {
    return str.match(/[()]|[^()]+/g);
}

function parse(toks, depth = 0) {
    let ast = [];

    while (toks.length) {
        let t = toks.shift();
        
        switch (t) {
            case '(':
                ast.push(parse(toks, depth + 1));
                break;
            case ')':
                if (!depth)
                    throw new SyntaxError('mismatched )');
                return ast;
            default:
                ast.push(t);
        }
    }

    if (depth) {
        throw new SyntaxError('premature EOF');
    }

    return ast;
}

function generate(el) {
    if (!Array.isArray(el))
        return el;

    while (el.length === 1 && Array.isArray(el[0]))
        el = el[0];

    return '(' + el.map(generate).join('') + ')';
}


//

let test = `
(((foo)))
((foo))
(foo)
(foo (bar))
((foo b)ar)
((((foo)) bar))
((((((foo))bar))baz))
((((((((foo))))))))
foo
`;

for (let s of test.trim().split('\n'))
    console.log(s, '=>', generate(parse(tokenize(s))));

这篇关于如何去掉不必要的括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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