Regex - How to remove strings inside brackets?

依然范特西╮ 提交于 2021-02-16 19:04:44

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!