首页 > 解决方案 > 具有嵌套结果的 Python 正则表达式

问题描述

我有以下“字符串”:

{ see 'identifier' }
     Some Text
     { see 'otherid' }
          Another Piece of Text
     { /see }
{ /see }

我想“提取”列表中的开始/结束,当然是考虑正则表达式。现在我做:

(\{ see([\s\S]+?)\}([\s\S]*?)\{ \/see \})

结果是:

Match 1
    1.  { see 'identifier' } Some Text { see 'otherid' } Another Piece of Text { /see }
    2.  'identifier'
    3.  Some Text { see 'otherid' } Another Piece of Text

但是,我希望能抓住两场比赛......

 Match 1:
    1.  { see 'identifier' } Some Text { see 'otherid' } Another Piece of Text { /see } { /see }
    2.  'identifier'
    3.  Some Text { see 'otherid' } Another Piece of Text { /see }

And Match 2:
    1.  { see 'otherid' } Another Piece of Text { /see }
    2.  'otherid'
    3.  Another Piece of Text

这可能在单个正则表达式中,还是我应该对此有不同的想法?

如果需要,这在 Py3.4+ 中,没有框架或任何可用的本地模块。可以安装 Pip,但不是首选。谢谢!

标签: pythonregexpython-3.xpattern-matching

解决方案


好的,所以当我们匹配字符串的结尾时,如下所示:

(\{ see([\s\S]+?)\}([\s\S]*?)\{ \/see \}$)

按预期返回第一个匹配项,但不返回第二个匹配项。

Match 1
1.  { see 'identifier' } Some Text { see 'otherid' } Another Piece of Text { /see } { /see }
2.  'identifier'
3.  Some Text { see 'otherid' } Another Piece of Text { /see }

这仍然不是我想要的,但如果需要的话会做的。


推荐阅读