为什么“[0-9]*”不匹配我的 Python 正则表达式中的 'abc',因为字符串中有零个或多个数字?

Why doesn't '[0-9]*' match 'abc' in my Python regular expression since there are zero or more digits in the string?

为什么这个正则表达式:

>>> r = re.compile("[0-9]*", re.DEBUG)

这样匹配:

>>> m = r.search("abc")
>>> m.group()
''

我希望它能匹配整个字符串 'abc',因为 'a' 满足条件,即匹配 0 个数字,然后贪婪匹配会在它的字符串中包含字符串 'abc'完整。

因为您的正则表达式只查找数字,而 abc 中没有任何数字。

简而言之,您的正则表达式匹配任何包含数字和空字符串的内容。

documentationsearch() 执行以下操作:

Scan through string looking for a location where this regular expression produces a match, and return a corresponding match object. 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.

因此,m 不是 None 的事实表明它找到了匹配项。 m.group() returns '' 显示 它匹配的内容 .

您搜索了 0 个或多个数字。它找到了 0 个或多个数字。它找到的确切位数是 0。因此,空字符串。

你问 "find me zero or more digits",所以它找到你零个或多个数字(零;空字符串)。

如果你想要"find me zero or more digits followed by zero or more other characters",你需要(使用.*模式)。 '[0-9]*' 匹配 'abc',因为 'abc' 包含请求表达式中未包含的字符(字母)。

>>> r = re.compile('[0-9]*.*')  # Note the very important ".*" that matches everything!
>>> r.search('abc').group()
'abc'

重点是"match"这个词。如果您的表达式不包含 [表示] 某个字符(例如 "a"),那么它不可能 匹配 包含该字符的字符串!您给定的表达式仅匹配由零个或多个数字组成的字符串 ,没有其他内容。因此它显然不匹配 'abc'.


正如 Tigerhawk 在评论中提到的,如果正则表达式中的 * 表示 "zero or more of the preceding pattern, or anything else",那将毫无用处,因为任何带有 * 的模式都会匹配所有字符串,所有时间!

使用否定字符Class

在你上面的 中,你说你希望 [0-9]* 匹配 abc 因为:

"abc" contains 0 digits.

您误解了字符 class 是什么,它包含原子。你的目前不是否定的断言。

如果不进行预编译,可能[^0-9]* 匹配。例如:

>>> import re
>>> re.search("[^0-9]*", "abc").group()
'abc'

这可能适合您的思维导图,但将否定字符 classes 视为 "not containing a range" 而不是 "not containing any of the included characters" 可能会让您在未来误入歧途。 YMMV.