javascript - 花括号的正则表达式
问题描述
我有一些包含这种结构的文本
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 时,如果支持,另一个选项可能是使用无限宽度的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);
推荐阅读
- python - 注册后如何将用户重定向到所需的链接?
- xcode - 在 iOS 模拟器上运行 React Native 应用程序时诊断进程的高 CPU 负载
- html - 输入类型电子邮件 - 删除默认样式
- python - 在 jupyter(Anaconda 3) 上安装 dlib
- vue.js - Vuetify:自适应 v-date-picker 宽度 v-dialog 和 v-menu
- python - pyplot 如何知道 pandas.DataFrame(...).cumprod().plot() 的输出所绘制的内容
- regex - 使用linux命令删除换行符
- javascript - 如何使用 Chart.js 在 Vue 中将计算属性与数据对象中 JSON 的数据一起用于时间轴
- postgresql - 使用 PostgreSQL 从 Well Known Text 创建 GeoJSON 输出
- node.js - 异步函数执行顺序错误