删除括号和任何(但仅限于)尾随空格的正则表达式是什么?
示例:"Hello [world] - what is this?"
会转换为"Hello - what is this?"
。
答案 0 :(得分: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?
答案 1 :(得分:1)
你可以让表达式在括号内的东西和尾随的空格之间交替:
str.replace(/\[[^\]]*\]|\s+$/g, '')
/g
修饰符用于匹配所有匹配项,而不是仅匹配第一个(默认值)。
<强>更新强>
如果[hello]
前面有空格,则该空格不会被移除,您需要另外.replace()
而不是替换:
str.replace(/\[[^\]]*\]/g, '').replace(/\s+$/, '');
答案 2 :(得分:0)
你可以这样做:
var result = mystring.replace(/^\s*\[[^]]+]\s*|\s*\[[^]]+]\s*$|(\s)\s*\[[^]]+]\s*/g, '$1');
答案 3 :(得分:0)
str.replace(/\[.+?\]\s*/g,'');