问题
I want to remove all words inside brackets and square brackets. I'm using this regex, but it only removes words inside brackets. It does not work with square brackets...
var str = 'hey [xx] (xhini) rexhin (zzz)';
var r = str.replace(/ *\([^)]*\)*\] */g, '');
r
should be hey rexhin
Any suggestions?
回答1:
You can use this regex:
var str = 'hey [xx] (xhini) rexhin (zzz)';
var r = str.replace(/(\[.*?\]|\(.*?\)) */g, "");
//=> hey rexhin
\[.*?\]
will find square brackets and string inside them\(.*?\)
will find round brackets and string inside them
You can also use (if square and round brackets are not nested):
var r = str.replace(/[(\[].*?[)\]] */g, "");
[(\[]
is a character class that finds(
or[
[)\]]
is a character class that finds)
or]
You can call trim()
to trim trailing space also.
回答2:
You could try the below regex.
> var str = "[xxx] hey [xx] (xhini) rexhin (zzz)";
undefined
> str.replace(/^(?:\[[^\]]*\]|\([^()]*\))\s*|\s*(?:\[[^\]]*\]|\([^()]*\))/g, "")
'hey rexhin'
DEMO
^(?:\[[^\]]*\]|\([^()]*\))\s*
would match the brackets as well as the following spaces which are present at the start (start of the line).|
OR\s*(?:\[[^\]]*\]|\([^()]*\))
Matches all the remaining brackets along with their preceding spaces.
来源:https://stackoverflow.com/questions/28517941/regex-how-to-remove-strings-inside-brackets