捕获以模式开头的多个组的正则表达式



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

  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']

如有任何建议,我们将不胜感激!

您可以通过Lookahead实现这一点。尝试以下模式:

${{.*?}}.*?(?=${{.*?}}|$)

演示

细分:

${{.*?}}    # 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.

最新更新