我试图删除使用正则表达式结束括号之后和之前的空间,问题是Safari不支持我的解决方案,是否有任何替代使用"向后看"功能吗?
我的字符串的例子:check IN [ "[hello world]*" ] OR host IN ( abc,123)
我期待得到:check IN ["[hello world]*"] OR host IN (abc,123)
我目前的解决方案:(?<=[([])s+|s+(?=[)]])
假设:
你总是想要删除
(
或[
之后的任何空格以及)
或]
之前的任何空格,以及你不会有
(
,)
,[
,或]
在文本字面量,你想保持不变(这真的只是一个子集#1,但我认为值得特别指出,因为这是一个大的假设)
…那么我不认为嵌套是一个问题,我们可以用正则表达式做到这一点。我认为你根本不需要到处看:
const result = str.replace(/([[(])s+|s+([])])/g, "$1$2");
// ^^^^^^^^^^ ^^^^^^^^^^
// after opening ( or [ −−−−−−−−/ |
// before closing ) or ] −−−−−−−−−−−−−−−−−−/
这里的技巧是我们使用了两次捕获,然后在替换中都使用;其中一个将始终是""
,而另一个将是"("
,"["
,")"
或"]"
。
的例子:
const str = `check IN [ "[hello world]*" ] OR host IN ( abc,123)`;
const result = str.replace(/([[(])s+|s+([])])/g, "$1$2");
// ^^^^^^^^^^ ^^^^^^^^^^
// after opening ( or [ −−−−−−−−/ |
// before closing ) or ] −−−−−−−−−−−−−−−−−−/
document.getElementById("before").textContent = str;
document.getElementById("result").textContent = result;
Before:
<pre id="before"></pre>
After:
<pre id="result"></pre>