简体   繁体   English

正则表达式无法提取括号中的单词

[英]RegEx to extract words in brackets not working

I am using RegEx and exec to extract words but it is returning the full first match, not all the matches separately. 我正在使用RegEx和exec提取单词,但它会返回完整的第一个匹配项,而不是分别返回所有匹配项。

The string is 'one two [three four] five [six] seven [nine ten]' . 字符串为'one two [three four] five [six] seven [nine ten]' The result should be 'three four' , 'six' , 'nine ten' , instead of '[three four] five [six] seven [nine ten]' . 结果应为'three four''six''nine ten' ,而不是'[three four] five [six] seven [nine ten]'

var text = "one two [three four] five [six] seven [nine ten]" 
var brackets = /\[([^]+)\]/g; 
var match; 
while (match = brackets.exec(text)) {
   console.log(match);
}

What am I missing? 我想念什么?

The problem is with the capturing group ([^]+) . 问题在于捕获组([^]+)

[^]+ matches any character, including newline as there is nothing specified in the negated character class. [^]+匹配任何字符,包括换行符,因为在否定的字符类中未指定任何内容。

Use the below regex 使用以下正则表达式

/\[([^[\]]+)\]/g

[^[\\]]+ : will match one or more characters except square brackets [ and ] . [^[\\]]+ :将匹配一个或多个除方括号[]以外的字符。

 var text = "one two [three four] five [six] seven [nine ten]" var brackets = /\\[([^[\\]]+)\\]/g; var match; while (match = brackets.exec(text)) { console.log(match[1]); } 


You can also use /\\[(.*?)\\]/g where .*? 您也可以使用/\\[(.*?)\\]/g其中.*? will match anything except ] . 将匹配除]以外的任何内容。

 var text = "one two [three four] five [six] seven [nine ten]" var brackets = /\\[(.*?)\\]/g; var match; while (match = brackets.exec(text)) { console.log(match[1]); } 

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

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