Python正则表达式花括号多行

时间:2016-07-11 18:29:55

标签: python regex multiline brackets

我在python中写作,让我们说我的文件看起来像这样:

aaa 

aaa "word" --sdsdrrr2 --sds {

test test 
}

aaa "word2" --sdsdd sdsd {

    fffsd
    ssss
}

aaa "word3" -sdksdld sdsd

{

    sdsdd
    sdsddd
    sdsdddd }

现在我想解析" word2"的输出包括前缀和后缀,因此输出将是:

aaa "word2" --sdsdd sdsd {

    fffsd
    ssss
}

尝试了以下代码:

f = open('/tmp/testt2')

for res in re.findall('aaa "word2" (.*?)}', f.read(), re.S):
    print res                                                                                                  

只有一些比赛没有开头和结尾的卷曲。

请注意:

  • 大括号之间的行数未知。
  • 正则表达是必须的
  • 如上面给出的示例所示,卷曲括号位置也是未知的(可以是间隔或不间隔,新行或不行等)。

感谢您的帮助,

1 个答案:

答案 0 :(得分:0)

你可以这样做:

^(?=.*"word2") # ^ - start of the line with pos. lookahead
[^{]+        # anything not a {
{[^}]+}      # followed by {, anything in between and a closing }

请参阅a demo on regex101.com以及a working fiddle on ideone.com