Python正则表达式检测字符串并找到该字符串对应的代码块

问题描述 投票:0回答:1

我有以下文字

text = '''
here are some examples
@with some text
@then some more text
@ some more@text @moretext probedetail
how are you
something is going on
}
how has it been
weather is good
'''

我想从上面的文本中提取从@直到}开始的字符串,条件是@应该最接近字符串'probedetail'但不在同一行,它应该在上面的行并以}结束

所以从上面的文字我期待

@then some more text
@ some more@text @moretext probedetail
how are you
something is going on
}
python regex python-regex
1个回答
0
投票

我的解决方案是

(@[^@]*?)(\n.*?probedetail[^}]*})

显然,

(\n.*?probedetail[^}]*})
部分是第一部分必须安装的锚点。
(@[^@]*?)
查找包含probedetail 的行之前的最后一个@,因为中间的所有内容都不能包含另一个@。我在 Notepad++ 中对此进行了测试,但将我的 \R 转换为 这对于 Python 来说似乎是正确的,如果我错了,我的错误。

© www.soinside.com 2019 - 2024. All rights reserved.