为什么模式匹配在Python中返回此结果?

时间:2014-03-23 10:23:59

标签: python regex pattern-matching

以下是我在https://developers.google.com/edu/python/regular-expressions

中阅读的代码
match = re.search(r'\d\s*\d\s*\d', 'xx1 2   3xx') =>  found, match.group() == "1 2   3"

match = re.search(r'\d\s*\d\s*\d', 'xx12  3xx') =>  found, match.group() == "12  3"

match = re.search(r'\d\s*\d\s*\d', 'xx123xx') =>  found, match.group() == "123"

我知道\d\s*\d\s*\d会匹配1 2 3,但我不知道为什么\d\s*\d\s*\d\d\s*\d\s*\d也可以分别匹配12 3和123?

有人可以帮我吗?

感谢。

2 个答案:

答案 0 :(得分:2)

Litterally,'\ d \ s * \ d \ s * \ d'表示“单个数字后跟任意数量的空格,后跟一个数字后跟任意数量的空格后跟一个数字”

由于0是“任意”数字,因此正则表达式匹配12 3和123没有问题。如果你想要一个正则表达式匹配1 2 3而不是12 3和123,请尝试'\ d \ s + \ d \ s + \ d'。

答案 1 :(得分:1)

\ s之后的'*'将匹配零到多个空格字符