簡體   English   中英

大括號的正則表達式

[英]Regular expression for Curly brackets

我有一些包含這種結構的文本

Any words that should be excluded {UH#sentence A*sentence B*sentence C} {UH#sentence D*sentence E*sentence F}  {UH#sentence G*sentence H} any other

我嘗試匹配

第 0 組:呃

第 1 組:句子 A

第 2 組:句子 B

第 3 組:句子 C

所以我有一個像這樣的正則表達式

\{(\w*[^i])#(^$|.+?)\*(^$|.+?)\*(^$|.+?)}\g

但是這個正則表達式也匹配只有一個“*”的結構,如果它們是多個。 在下面的示例中,第 3 組在不應該匹配時進行了匹配。

Any words that should be exclued {UH#sentence G*sentence H} excluded {UH#sentence A*sentence B dzqd*sentence C} {UH#sentence D*sentence E*sentence F}   any other

第 3 組:句子 H} 排除{UH#sentence A

演示鏈接https://regex101.com/r/QQASlJ/1/ 正則表達式將在 javascript 中使用。

您可以通過首先匹配字符串的格式並使用 2 個捕獲組來實現它。

{(\w+)#([^{}]+)}

模式匹配:

  • {匹配開頭卷曲
  • (\\w+)捕獲第 1 組,匹配 1+ 個字字符
  • #逐字匹配
  • ([^{}]+)捕獲組 2 ,匹配 1+ 除{}之外的任何字符
  • }匹配右花

正則表達式演示

然后您可以在第二步中處理捕獲組,您可以在*上拆分組 2

 const s = "Any words that should be excluded {UH#sentence A*sentence B*sentence C} {UH#sentence D*sentence E*sentence F} {UH#sentence G*sentence H} any other"; const regex = /{(\\w+)#([^{}]+)}/g; const result = Array.from( s.matchAll(regex), m => [m[1]].concat(m[2].split(/\\s*\\*/)) ); console.log(result);


當您使用 Javascript 時,另一個選項可能是使用無限寬度的后視(如果支持) 它不提供單獨的組值,而只提供匹配項。

(?<={(?:\w+#[^{}]*)?)[^{}*#]+(?=[^{}]*})

正則表達式演示

 const s = "Any words that should be excluded {UH#sentence A*sentence B*sentence C} {UH#sentence D*sentence E*sentence F} {UH#sentence G*sentence H} any other"; const regex = /(?<={(?:\\w+#[^{}]*)?)[^{}*#]+(?=[^{}]*})/g; const result = Array.from(s.matchAll(regex), m => m[0]); console.log(result);

在 RegEx 中有你不想要的東西

您正在使用.+? (這與.*不一樣),它也匹配大括號}

你可以說“除了大括號之外的所有字符” [^}]*

{(\w*[^i])#(^$|[^}]*)\*(^$|[^}]*)\*(^$|[^}]*)}

這適用於您給出的示例。

暫無
暫無

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

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