删除括号前后的所有空格 [英] Remove all spaces before and after parentheses
问题描述
我想在括号前 和 之后删除一个或多个空格.跟随这篇文章,其中使用以下正则表达式解决了PHP的问题
I would like to remove one or more spaces before and after any parentheses. Following this post where the issue has been solved for PHP with the following regex
(?<=[([]) +| +(?=[)\]])
现在,我想在 Javascript 中执行相同的操作,但是Javascript正则表达式引擎的前瞻性和后瞻性与PHP相同.我设法使以下正则表达式至少在Javascript中有效,但是它删除了所有空格:
now I would like to do the same in Javascript but Javascript regex engine does not have the same lookahead and lookbehind as PHP. I managed to make the following regex at least work in Javascript but it removes all spaces:
?![([]) +| +(?=[)\]])
请参见 Regex101测试.
给出字符串:
This is ( a sample ) [ string ] to play with
预期结果:
This is (a sample) [string] to play with
推荐答案
您可以改用捕获组,并用其占位符替换以恢复结果中的括号/括号:
You may use capturing groups instead and replace with their placeholders to restore the bracket/parentheses in the result:
.replace(/([([])\s+|\s+([)\]])/g, "$1$2");
请参见 regex演示
详细信息
-
([[[[])\ s +
-组1捕获(
或[
(用$ 1引用
(来自字符串替换模式),然后是1+空格 -
|
-或 -
\ s +([] \]])
-1个以上的空格,后跟一个)
或]
捕获到第2组中(称为字符串替换模式中的$ 2
)
([([])\s+
- Group 1 capturing either a(
or a[
(referred to with$1
from the string replacement pattern) and then 1+ whitespaces|
- or\s+([)\]])
- 1+ whitespaces followed with a)
or]
captured into Group 2 (referred to with$2
from the string replacement pattern)
JS演示:
var strs = ['This is ( a sample ) [ string ] to play with',
'This is ( a sample ) [ string] to play with'];
var rx = /([([])\s+|\s+([)\]])/g;
for (var s of strs) {
console.log(s+ " =>\n"+ s.replace(rx, "$1$2"));
}
这篇关于删除括号前后的所有空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!