2

什么是删除括号和任何(但只有)尾随空格的好正则表达式?

示例:"Hello [world] - what is this?"将转换为"Hello - what is this?".

4

4 回答 4

2

使用以下正则表达式。它将删除括号及其尾随空格。

/(\s\s)*(\s(?=\[.*?\]\s))*\[.*?\](\s\s)*/g

用法:

var testStr = "Hello [world] - what is this?";
console.log(testStr.replace(/(\s\s)*(\s(?=\[.*?\]\s))*\[.*?\](\s\s)*/g, ""));

输入/输出:

Input: Hello [world] - what is this?            Output: Hello - what is this?
Input: Hello [world] - what  is  this?          Output: Hello - what  is  this?
Input: Hello [world] - what is     this?        Output: Hello - what is     this?
Input: Hello      [world] - what is this?       Output: Hello - what is this?
Input: Hello      [world]     - what is this?   Output: Hello - what is this?
Input: Hello [world]       - what is this?      Output: Hello - what is this?
Input: Hello [world]- what is this?             Output: Hello - what is this?
Input: Hello       [world]- what is this?       Output: Hello - what is this?
Input: Hello[world] - what is this?             Output: Hello - what is this?
Input: Hello[world]       - what is this?       Output: Hello - what is this?
Input: Hello[world]- what is this?              Output: Hello- what is this? 
于 2013-06-14T15:48:44.297 回答
1

您可以让表达式在括号中的内容和尾随空格之间交替:

str.replace(/\[[^\]]*\]|\s+$/g, '')

/g修饰符用于匹配所有出现而不是仅匹配第一个(默认)。

更新

[hello]前面有空格的情况下,该空格不会被删除,您需要另一个.replace()而不是交替:

str.replace(/\[[^\]]*\]/g, '').replace(/\s+$/, '');
于 2013-06-14T15:47:10.053 回答
0

你可以这样做:

var result = mystring.replace(/^\s*\[[^]]+]\s*|\s*\[[^]]+]\s*$|(\s)\s*\[[^]]+]\s*/g, '$1');
于 2013-06-14T15:46:05.390 回答
0
str.replace(/\[.+?\]\s*/g,'');
于 2013-06-14T15:46:26.220 回答