什么是删除括号和任何(但只有)尾随空格的好正则表达式?
示例:"Hello [world] - what is this?"
将转换为"Hello - what is this?"
.
什么是删除括号和任何(但只有)尾随空格的好正则表达式?
示例:"Hello [world] - what is this?"
将转换为"Hello - what is this?"
.
使用以下正则表达式。它将删除括号及其尾随空格。
/(\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?
您可以让表达式在括号中的内容和尾随空格之间交替:
str.replace(/\[[^\]]*\]|\s+$/g, '')
/g
修饰符用于匹配所有出现而不是仅匹配第一个(默认)。
更新
在[hello]
前面有空格的情况下,该空格不会被删除,您需要另一个.replace()
而不是交替:
str.replace(/\[[^\]]*\]/g, '').replace(/\s+$/, '');
你可以这样做:
var result = mystring.replace(/^\s*\[[^]]+]\s*|\s*\[[^]]+]\s*$|(\s)\s*\[[^]]+]\s*/g, '$1');
str.replace(/\[.+?\]\s*/g,'');