简体   繁体   English

正则表达式 - 如何删除括号内的字符串?

[英]Regex - How to remove strings inside brackets?

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 r应该hey rexhin

Any suggestions? 有什么建议?

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. 您也可以调用trim()来修剪尾随空格。

You could try the below regex. 你可以试试下面的正则表达式。

> var str = "[xxx] hey [xx] (xhini) rexhin (zzz)";
undefined
> str.replace(/^(?:\[[^\]]*\]|\([^()]*\))\s*|\s*(?:\[[^\]]*\]|\([^()]*\))/g, "")
'hey rexhin'

DEMO DEMO

  • ^(?:\\[[^\\]]*\\]|\\([^()]*\\))\\s* would match the brackets as well as the following spaces which are present at the start ( start of the line ). ^(?:\\[[^\\]]*\\]|\\([^()]*\\))\\s*将匹配括号以及开头处的以下空格( 行的开头) )。

  • | OR 要么

  • \\s*(?:\\[[^\\]]*\\]|\\([^()]*\\)) Matches all the remaining brackets along with their preceding spaces. \\s*(?:\\[[^\\]]*\\]|\\([^()]*\\))匹配所有剩余的括号及其前面的空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM