【问题标题】:python re.findall weird behaviourpython re.findall 奇怪的行为
【发布时间】:2013-04-01 05:08:48
【问题描述】:
>>> text =\
... """xyxyxy testmatch0
... xyxyxy testmatch1
... xyxyxy
... whyisthismatched1
... xyxyxy testmatch2
...  xyxyxy testmatch3
... xyxyxy
... whyisthismatched2
... """
>>> re.findall("^\s*xyxyxy\s+([a-z0-9]+).*$", text, re.MULTILINE)
[u'testmatch0', u'testmatch1', u'whyisthismatched1', u'testmatch2', u'testmatch3', u'whyisthismatched2']

所以我的期望是不匹配包含“whyisthismatched”的行。

Python re 文档声明如下:

(点)在默认模式下,它匹配除 a 之外的任何字符 新队。如果指定了 DOTALL 标志,则匹配任何 包括换行符的字符。

我的问题是这是否真的是预期的行为或错误。 如果预计有人请解释为什么这些行匹配以及我应该如何修改我的模式以获得我期望的行为:

[u'testmatch0', u'testmatch1', u'testmatch2', u'testmatch3']

【问题讨论】:

  • 换行符可能包含在 \s 和 re.MULTILINE ...我认为至少

标签: python regex findall


【解决方案1】:

\s 字符类而言,换行符也是空格。如果你想匹配空格,你只需要匹配[ ]

>>> re.findall("^\s*xyxyxy[ ]+([a-z0-9]+).*$", text, re.MULTILINE)
[u'testmatch0', u'testmatch1', u'testmatch2', u'testmatch3']

【讨论】:

  • 呸,你的速度更快:P 一如既往(感谢我回答的信息:))
猜你喜欢
  • 2019-11-03
相关资源
最近更新 更多