Javascript 使用正则表达式匹配括号顺序和条件

Javascript 使用正则表达式匹配括号顺序和条件,javascript,regex,Javascript,Regex,我想应用正则表达式来查找并替换输入字符串中不需要的括号和运算符 以下是我可能的输入:从a到d的4种类型。[无效输入] a). 1 and (2 or 3) () b). ( and 2) c). (or 4) d). () a). 1 and 2 b). (1 and 2) c). 1 and (2 or 4) 这4个都是无效案例,有效案例应为[有效输入] a). 1 and (2 or 3) () b). ( and 2) c). (or 4) d). () a). 1 and 2 b)

我想应用正则表达式来查找并替换输入字符串中不需要的括号和运算符

以下是我可能的输入:从a到d的4种类型。[无效输入]

a). 1 and (2 or 3) ()
b). ( and 2)
c). (or 4)
d). ()
a). 1 and 2
b). (1 and 2)
c). 1 and (2 or 4)
这4个都是无效案例,有效案例应为[有效输入]

a). 1 and (2 or 3) ()
b). ( and 2)
c). (or 4)
d). ()
a). 1 and 2
b). (1 and 2)
c). 1 and (2 or 4)
基于这个要求,我已经编写了正则表达式,但我已经编写了两个部分,需要帮助将它们连接到单个正则表达式

a). ([(]+[\s]*[)]+) -> to find the empty parenthesis
b). (([(]+[\s]*[and|or]+[\s]*)) -> to find cases like b or c in invalid inputs.
请建议一种结合上述内容的方法。此外,我想删除输入中的无效部分,这可以在类似string.replace(regex)的javascript中完成

请对此过程进行分析并提出意见

/\((\s*|\s*(?:and|or)\s*\d+\s*|\s*\d+\s*(?:and|or)\s*|\s*(?:and|or)\s*)\)/
检查括号对内容的正则表达式:空、左侧缺少操作数、右侧缺少操作数或根本没有操作数

但是要小心!这既不检查未括在括号内的表达式的有效性,也不符合科林·费恩(Colin Fine)已经提到的要求。如果您愿意检查,我建议从内到外更换:

var s = string;
var oneoperator = /^\s*\d+\s*(and|or)\s*\d+\s*$/;
while (true) {
    s = s.replace(/\(([^)])\)/, function(all, inner) {
        if (inner.match(oneoperator)
            return "0"; // or any other valid operand
        else
            throw new SyntaxError("Math Syntax mismatch");
    });
    if (s.match(oneoperator))
        break; // return true
}
// to be improved

不清楚的是,您是只想验证输入,还是想试探性地从错误中清除输入。在我看来,第二种方法行不通。我想你误解了方括号“[”和“]”。例如,[和|或]表示六个字符‘a’、‘n’、‘d’、‘|’、‘o’、‘r’中的任何一个。这种问题不适用于regexp。基本上,您拥有的是递归语法,而regexp无法处理它们。因为它在递归方面受到限制,只允许一个嵌入级别,所以在regexp中是可能的,但解决方案可能会很复杂和不清楚。@ColinFine:更具体地说,它不适合JavaScript正则表达式。像.NET、PHP或Perl中的现代正则表达式引擎都支持递归?例如,您能保证永远不会遇到嵌套括号吗?或者至少保证嵌套的上限?