Python regex,用于查找两个\n \n和\n \n之间的所有内容

2024-09-22 16:33:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个大的文本字符串,与init有几个块看起来非常相似

text = '\n\n(d)In the event of this happens a Fee 
of \xc2\xa32,000 gross, on each such occasion.\n\n'

使用下面的代码,我可以找到所有的money实例:

^{pr2}$

但是这只返回逗号In the event of this happens a Fee of \xc2\xa32,000 gross而不是整个块,我希望返回提到Unicode for British-lb \xa3的块


Tags: ofthe字符串textin文本eventinit
2条回答

我建议使用以下正则表达式:

text = ('\n\nthis is not wanted\n\n'
        '(d)In the event of this happens a Fee\n'
        'of \xc2\xa32,000 gross, on each such occasion.\n\n'
        'another wanted line with pound: \xc2\xa31,000\n\n'
        'this is also not wanted\n\n')

re.findall(r'(?:.+\n)*.*\xa3(?:.+\n)*', text)

这将查找至少包含一个\xa3的非空行的所有多行块。在

正如@wiktor stribiżew在一篇评论中指出的,这只会找到那些在井号符号后面有另一个字符的块;这似乎是您想要的,所以没有问题,但应该提到。在

试试这个:

import re 
text = '\n\nblock1\xa3block1.\n\nblock2\x80block2\n\nblock3\xa3block3\n\n' 
result= re.findall('.*\xa3.*', text) #capture only blocks containing pound symbol and discards block2 that contains euro 
print(result) 

相关问题 更多 >