Skip to main content
 首页 » 编程设计

python re.findall 奇怪的行为

2025年05月04日17lonelyxmas

>>> 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 文档说明如下:

(Dot.) In the default mode, this matches any character except a newline. If the DOTALL flag has been specified, this matches any character including a newline.

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

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

请您参考如下方法:

就 \s 字符类而言,换行符也是空白。如果您只想匹配 spaces,则需要匹配 [ ]:

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