[英]use of regex for matching the parenthesis ordering and conditions
I wanted to apply the regular expressions to find and replace the unwanted parenthesis and operators in the input string. 我想应用正则表达式来查找和替换输入字符串中不需要的括号和运算符。
Here is the possible input for me: 4 types from a through d. 这是我的可能输入:从a到d的4种类型。 [Invalid Inputs]
[无效输入]
a). 1 and (2 or 3) ()
b). ( and 2)
c). (or 4)
d). ()
all these 4 are invalid cases , the valid ones should be as [Valid Inputs] 所有这4个无效案例,有效案例应为[有效输入]
a). 1 and 2
b). (1 and 2)
c). 1 and (2 or 4)
Based on this requirement, i have written the regex, but i have written in 2 parts and need help in joining them to a single regex. 基于此要求,我编写了正则表达式,但是我分两部分编写了文档,需要帮助将它们加入到单个正则表达式中。
a). ([(]+[\s]*[)]+) -> to find the empty parenthesis
b). (([(]+[\s]*[and|or]+[\s]*)) -> to find cases like b or c in invalid inputs.
Kindly suggest a way to combine the above. 请提出一种结合以上内容的方法。 further i want to do removal of the invalid parts in the inputs, which i can do in javascript like string.replace(regex).
此外,我想删除输入中的无效部分,这可以在JavaScript中像string.replace(regex)这样进行。
Kindly analyze and give comments on this process. 请对此过程进行分析并提出意见。
/\((\s*|\s*(?:and|or)\s*\d+\s*|\s*\d+\s*(?:and|or)\s*|\s*(?:and|or)\s*)\)/
is a Regex that checks for the content of a bracket pair: either empty, missing operand on the left, missing operand on the right or no operands at all. 是一个正则表达式,用于检查方括号对的内容:空,左侧缺少操作数,右侧缺少操作数或完全没有操作数。
But watch out! 但是要当心! This neither checks for validity of un-bracketed expressions, nor is it rekursive, as Colin Fine already mentioned.
正如Colin Fine已经提到的那样,这既不会检查未括弧的表达式的有效性,也不是递归的。 If you liked to check for that, I'd propose to replace from inside up:
如果您想检查一下,我建议从内而外替换:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.