簡體   English   中英

RegEx用於捕獲嵌套括號中的值

[英]RegEx for capturing values in nested brackets

我試圖使用正則表達式來匹配兩個字符之間的內部文本,但我得到了錯誤的文本

我嘗試將[Az] *代替。*僅用於匹配內部文本而且它有效。 但我也需要匹配非字母字符。

/\[?(,? ?\[(\[(.+)-(.+)\])\])\]?/g

這是我的正則表達式,我想匹配方括號之間的字符:

[[[ hello-hello]],[[hi -hi]]]

粗體字符是匹配的字符。

我期望匹配匹配1中的[[[ hello-hello ]],[[hi-hi]]]和匹配2中的[[[hello-hello]],[[ hi-hi ]]]匹配。

這是我提出的正則表達式:

\[+([a-z- A-Z]+)\]+

演示

我會用這樣的東西:

\[(?!\[)([^\]]*)\]

這將匹配[字符,如果沒有后跟[字符。 然后它將匹配在組1中捕獲它們的任何數量的非]字符。然后匹配一個]字符。

 const text = "[[[hello-hello]],[[hi-hi]]]"; const regex = /\\[(?!\\[)([^\\]]*)\\]/g; var match; while (match = regex.exec(text)) { console.log(match); } 

或者,您可以省略捕獲組並刪除每個匹配的第一個和最后一個字符。

 const text = "[[[hello-hello]],[[hi-hi]]]"; const regex = /\\[(?!\\[)[^\\]]*\\]/g; console.log( text.match(regex) .map(match => match.slice(1, -1)) ); 

如果需要[]之間的所有內容,那么我們可能會將表達式簡化為:

(?:\[+)(.+?)(?:\]+)

在這里,我們捕獲此捕獲組中可能需要的子字符串:

(.+?)

然后,我們使用兩個非捕獲組在其左側和右側添加兩個邊界:

(?:\[+)
(?:\]+)

演示

 const regex = /(?:\\[+)(.+?)(?:\\]+)/g; const str = `[[[hello-hello]] [[hi-hi]]] [[hi hi]]]`; const subst = `$1`; // The substituted value will be contained in the result variable const result = str.replace(regex, subst); console.log('Substitution result: ', result); 

在此輸入圖像描述

正則表達式

如果不需要此表達式,可以在regex101.com中對其進行修改/更改。

RegEx電路

jex.im可視化正則表達式:

在此輸入圖像描述

您可以使用1個捕獲組來捕獲您的值。

連字符前后的值可以是使用否定字符類匹配的匹配\\[([^][\\n-]+匹配不是開括號或右括號,連字符或換行符。

在你的模式中,你使用一個點,它將匹配除換行符之外的任何字符,因此否定的字符類包含一個換行符以防止交叉行。

\[([^\][\n-]+-[^\][\n-]+)]

說明

  • \\[匹配[
  • (開始捕獲組
    • [^\\][\\n-]+不否定的字符類,匹配1+倍][-或換行符
    • -比賽-
    • [^\\][\\n-]+匹配1+倍不][-或換行符
  • )關閉捕獲組
  • ]匹配] char

正則表達式演示

 const regex = /\\[([^\\][\\n-]+-[^\\][\\n-]+)]/g; const str = `[[[hello-hello]],[[hi-hi]]]`; let m; while ((m = regex.exec(str)) !== null) { if (m.index === regex.lastIndex) { regex.lastIndex++; } console.log(m[1]); } 

正則表達式

(?<=\[)([a-z- A-Z]+)(?=\])

(?<=\\\\[) :從括號開始,但不包含括號。

(?=\\\\]) :以支架結束,但不包含支架。

詳細說明可在此鏈接中找到。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM