regex - 一个正则表达式捕获多个以模式开头的组
问题描述
我试图找出一个正则表达式,它将捕获字符串中的多个组,其中每个组的定义如下:
- 小组的标题以
${{
- 后面可能有一个可选字符串
- 该组的标题以
}}
- 可选内容可能跟在标题后面
一个例子是
'${{an optional title}} some optional content'
以下是一些输入和预期结果的示例
输入 1:'${{}} some text '
结果1:['${{}} some text ']
输入 2:'${{title1}} some text1 ${{title 2}} some text2'
结果 2:['${{title1}} some text1 ', '${{title 2}} some text2']
输入 3(没有第三组,因为缺少第二个结尾大括号)
'${{title1}} some text1 ${{}} some text2 ${{title2} some text3'
结果 3['${{title1}} some text1 ', '${{}} some text2 ${{title2} some text3']
输入 4(一个内容为空的组,紧随其后的是另一个组)
'${{title1}}${{}} some text2'
结果 4['${{title1}}', '${{}} some text2']
任何建议将不胜感激!
解决方案
您可以通过 Lookaheads 实现这一目标。尝试以下模式:
\$\{\{.*?\}\}.*?(?=\$\{\{.*?\}\}|$)
演示。
分解:
\$\{\{.*?\}\} # Matches a "group" (i.e., "${{}}") containing zero or more chars (lazy).
.*? # Matches zero or more characters after the "group" (lazy).
(?= # Start of a positive Lookahead.
\$\{\{.*?\}\} # Ensure that the match is either followed by a "group"...
| # Or...
$ # ..is at the end of the string.
) # Close the Lookahead.
推荐阅读
- c# - C# 将对泛型方法的引用传递给另一个方法
- javascript - 克隆了我的阵列,但原始阵列不断被修改。为什么?
- json - 如何使用 JSON 输出中的 jq 计算平均值
- gradle - 调度||自动化 MarkLogic 数据中心流程/自定义步骤的最佳方式
- javascript - Microsoft Edge 扩展 Auth0 实施 - 无法加载授权页面
- mongodb - MongoDB 4.2 聚合查询在二级应用过滤器
- r - 为什么在 R 中使用合并函数会创建重复项?
- r - 合并和排序R中的任意两个排序数组
- debian - 如何挂载 btrfs 子卷?
- javascript - Recharts:隐藏值未定义的栏