简体   繁体   English

Python正则表达式花括号多行

[英]Python regex curly brackets multiline

I'm writing in python and let's say I have a file looking like this: 我正在写python,让我说我有一个文件看起来像这样:

aaa 

aaa "word" --sdsdrrr2 --sds {

test test 
}

aaa "word2" --sdsdd sdsd {

    fffsd
    ssss
}

aaa "word3" -sdksdld sdsd

{

    sdsdd
    sdsddd
    sdsdddd }

now I want to parse output for "word2" including prefix and suffix, so output will be: 现在我想解析“word2”的输出,包括前缀和后缀,因此输出将是:

aaa "word2" --sdsdd sdsd {

    fffsd
    ssss
}

tried the following code: 尝试了以下代码:

f = open('/tmp/testt2')

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

only got some of the matches without the beginning and the ending curly. 只有一些比赛没有开始和结束卷曲。

Please note: 请注意:

  • Number of lines between the curly brackets is unknown. 大括号之间的行数未知。
  • Regex is a must 正则表达式是必须的
  • Curly brackets positions are also unknown (can be spaced or not, new line or not etc) like in the example given above. 如上面给出的例子中,卷曲括号位置也是未知的(可以是间隔或不间隔,新线或不是等)。

Thanks for any help, 谢谢你的帮助,

You could do it like: 你可以这样做:

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

See a demo on regex101.com as well as a working fiddle on ideone.com . 查看regex101.com上的演示以及ideone.com上 的工作小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM