首页 > 解决方案 > 花括号的正则表达式

问题描述

我有一些包含这种结构的文本

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 中使用。

标签: javascriptregex

解决方案


您可以通过首先匹配字符串的格式并使用 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 时,如果支持,另一个选项可能是使用无限宽度的lookbehind 。它不给出单独的组值,而只给出匹配项。

(?<={(?:\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);


推荐阅读