【问题标题】:Match text including a line break with re [duplicate]用re匹配包含换行符的文本[重复]
【发布时间】:2020-12-17 13:45:30
【问题描述】:

我有一个 Python 代码,它解析一个文本文件并在标签 @(my word) 中查找单词的实例。为此,我使用,例如:

import re

DEF_RE = r"(@\()(?P<text>.+?)\)"

sometext = "find the @(tagged text)."

m = re.search(DEF_RE, sometext)

print(m.group("text"))
tagged text

但是,如果文件包含分成两行的标记文本,则上述方法不起作用,例如,

sometext = "find the @(tagged\ntext)."

m = re.search(DEF_RE, sometext)

print(m)
None

有没有办法改变我的正则表达式字符串以允许文本被分割成一行?

【问题讨论】:

  • 打开 DOTALL 标志。re.DOTALL。或将.+? 替换为(?:.|[\n\r])+?
  • 在搜索之前替换所有换行符怎么样?
  • 试试r"@\(.*[\n ]*.*\)"

标签: python regex re


【解决方案1】:

searching 时应该打开DOTALL 标志。

您可以将re.search(DEF_RE, sometext) 替换为re.search(DEF_RE, sometext, flags=re.DOTALL)

Proof

【讨论】:

  • 永远不要建议(?:.|[\n\r])+?。有众所周知的re.S / re.DOTALL / (?s) 解决方案,无需一遍又一遍地重复。
  • @WiktorStribiżew ok
猜你喜欢
  • 2021-05-14
  • 1970-01-01
  • 1970-01-01
  • 2013-01-27
  • 1970-01-01
  • 2017-01-18
  • 2018-05-11
  • 1970-01-01
  • 2013-04-03
相关资源
最近更新 更多