首页 > 解决方案 > 一个正则表达式捕获多个以模式开头的组

问题描述

我试图找出一个正则表达式,它将捕获字符串中的多个组,其中每个组的定义如下:

  1. 小组的标题以${{
  2. 后面可能有一个可选字符串
  3. 该组的标题以}}
  4. 可选内容可能跟在标题后面

一个例子是
'${{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']

任何建议将不胜感激!

标签: regexdart

解决方案


您可以通过 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.

推荐阅读