Python 正则表达式搜索总是错误的?

标签 python regex

我很确定我在这里遗漏了一些非常基本的东西,因为我通常对 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/

相关文章:

c# - 正则表达式在特定单词后立即查找单词

regex - 正则表达式 (\S+?) 与 (\S+))

python regex - 找到几个可选字符分组之一

python - Stacked DenoisingAutoencoders 的 Theano 实现 - 为什么 dA 层的输入相同?

Python 正则表达式匹配 C++ typedef'd 枚举

java - 正则表达式获取“符号”之间的文本

python - 在 Python 中展平字符串列表以及字符串列表和列表

python - django错误:1146, "Table ' basic_project.topics_topic'不存在”

python - 无法替换 pandas 列中包含 $ 的字符串

python - Flask:避免循环导入的应用程序结构