【问题标题】:Python regex for finding everything inbetween two \n\n and \n\n用于查找两个 \n\n 和 \n\n 之间的所有内容的 Python 正则表达式
【发布时间】:2016-10-31 12:53:16
【问题描述】:

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

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

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

import re
re.finall('\xa3(.*)', text)

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

【问题讨论】:

  • 为什么不只是'\n\n(.*)\n\n'
  • @PatrickHaugh 不会返回文本字符串中的每个文本块吗?我希望将其与'\xa3(.*)'
  • \n\n(.*\xa3.*)\n\n
  • 有趣的是,如果双 \ns 之间只有 1 行,\n\n(.*\xa3.*)\n\n 将起作用。分隔符之间可以有 2 行(即一个换行符)吗?这是在上面示例中Fee 之后的换行符吗?如果是,丹尼尔的正则表达式won't work.
  • @DanielLee 正如建议的那样,它仅适用于双 \n 之间的 1 行,在整个文档中,分隔符之间可以有 2 或 3 个换行符

标签: python regex wildcard


【解决方案1】:

我提出这个正则表达式:

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 在评论中指出的那样,这只会找到那些在井号符号后面有另一个字符的块;这似乎是你想要的,所以没问题,但应该提到。

【讨论】:

  • 这个r'(?:.+\n)*.*\xa3(?:.+\n)*' 是展开模式的一个很好的例子,但是第二个+ 量词不会让模式匹配子字符串中行尾的符号。
  • 对。在这种情况下,它似乎是正确的。 OP 期望在英镑符号(数字)之后有一些东西。但值得一提,谢谢!
【解决方案2】:

试试这个:

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) 

【讨论】:

  • 当然,我们试过了。你?原始输入是text = '\n\n(d)In the event of this happens a Fee\n of \xc2\xa32,000 gross, on each such occasion.\n\n'。您的正则表达式不会返回双换行符分隔符之间的字符串部分。
猜你喜欢
  • 2012-09-15
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 2021-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多