我很确定我在这里遗漏了一些非常基本的东西,因为我通常对 Python 和 Regex 没问题。我正在查看提供的字符串是否至少包含一个数字,这是我正在使用的命令行,但总是出错...
>>> import re
>>> test_string = "123567890"
>>> pat = re.compile("[0-9]")
>>> pat.search(test_string) == True
False
在发布这篇文章之前,我尝试了一些其他的排列方式,但都没有走得太远,我做错了什么?
最佳答案
pat.search
返回的不是 bool 值而是 MatchObject所以你的比较会失败:
In [9]: p = pat.search(test_string)
In [10]: p
Out[10]: <_sre.SRE_Match at 0x3cfa608>
In [11]: type(p)
Out[11]: _sre.SRE_Match
参见 re.search文档:
re.search(pattern, string, flags=0)
Scan through string looking for a location where the regular expression pattern produces a match, and return a corresponding MatchObject instance. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.
关于Python 正则表达式搜索总是错误的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11278375/