簡體   English   中英

正則表達式無法提取括號中的單詞

[英]RegEx to extract words in brackets not working

我正在使用RegEx和exec提取單詞,但它會返回完整的第一個匹配項,而不是分別返回所有匹配項。

字符串為'one two [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);
}

我想念什么?

問題在於捕獲組([^]+)

[^]+匹配任何字符,包括換行符,因為在否定的字符類中未指定任何內容。

使用以下正則表達式

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

[^[\\]]+ :將匹配一個或多個除方括號[]以外的字符。

 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]); } 


您也可以使用/\\[(.*?)\\]/g其中.*? 將匹配除]以外的任何內容。

 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