问题描述
我想从javascript正则表达式中的表达式中删除那些为空的括号。例如 (() a and b)
-> ( and b)
。它也适用于 ( ( ( () ) )a and b)
-> (a and b)
的情况。基本上它应该从表达式中删除不必要的括号。我在写正则表达式
expression.replace(/(\s)/,'');
但这不起作用。有人可以帮忙吗?
解决方法
有不同的方法可以做到这一点,一个简单的迭代方法是反复删除空括号(需要在正则表达式中转义!):
function remove_empty_parens(str) {
let new_str = str.replace(/\(\s*\)/,'');
return new_str == str ? str : remove_empty_parens(new_str);
}
,
你可以使用
const text = "( ( ( () ) )a and b)";
let output = text;
while (output != (output = output.replace(/\(\s*\)/g,"")));
console.log(output);
/\(\s*\)/g
正则表达式匹配所有不重叠的
-
\(
- 文字(
字符 -
\s*
- 零个或多个空白字符 -
\)
- 文字)
字符。
while (output != ...)
循环确保根据需要进行多次替换,以删除开/关括号之间的所有子字符串,直到找不到更多匹配项为止。
您可以使用 /\(\s*\)/
删除未嵌套的对:
- 使用
\(
和\)
对括号进行转义,因为它们在正则表达式中具有特殊含义。 - 使用
\s*
允许零个或多个空白字符而不是一个。
但是,由于 pumping lemma,您不能使用真正的正则表达式以这种方式删除嵌套括号。 JavaScript 中的正则表达式不是理论上的“正则”表达式,所以也许可以做一些事情(例如使用反向引用),但我没有立即看到它。
一种可能的解决方案是重复应用上述正则表达式,直到字符串不再变化。
,这个例子为我运行:
let expression1 = "( ( ( () ) )a and b)"
let last_expression1 = ""
let regex = /(\(\ *\))+/g;
while (expression1 != last_expression1) {
last_expression1 = expression1
expression1 = expression1.replace (regex,'')
}
console.log(expression1)
正确的正则表达式是:
/(\(\ *\))+/g