gpt4 book ai didi

Python 正则表达式陷阱

转载 作者:行者123 更新时间:2023-11-28 19:51:02 25 4
gpt4 key购买 nike

你能解释一下为什么第一个正则表达式不匹配吗?

Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05) 
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
>>> import re
>>> re.match(r'\d','.0')
>>> re.match(r'.\d','.0')
<_sre.SRE_Match object at 0x109adbd30>

最佳答案

re.match()尝试从字符串的开头匹配。

使用re.search()相反,如果您想在字符串中的任何位置找到匹配项。

PS:您可能想要转义 .,因为它是一个匹配任何 1 字符的元字符(因此 x0 将匹配您的第二个字符示例)。

>>> re.match(r'\.\d', 'x0')
>>> re.match(r'.\d', 'x0')
<_sre.SRE_Match object at 0x01F67138>

1 除了换行符,除非 re.DOTALL被使用。

关于Python 正则表达式陷阱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7519493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com