*在Python正则表达式匹配中有*副作用吗?

时间:2014-06-24 14:53:15

标签: python regex

我正在学习Python的正则表达式,以下是按照我的预期工作:

>>> import re
>>> re.split('\s+|:', 'find   a str:s2')
['find', 'a', 'str', 's2']

但是当我将+更改为*时,输出对我来说很奇怪:

>>> re.split('\s*|:', 'find  a str:s2')
['find', 'a', 'str:s2']

如何在Python中解释这种模式?

2 个答案:

答案 0 :(得分:8)

副作用'你看到的是re.split()只会在长于0个字符的匹配项上拆分。

\s*|:模式匹配 在零个或多个空格上,:上,以先到者为准 。但零空格匹配到处。在匹配空间大于零的位置,进行拆分。

由于每次考虑分割字符时\s*模式都匹配,因此永远不会考虑下一个选项:

分割非空匹配为called out explicitly in the re.split() documentation

  

请注意, split 绝不会在空模式匹配上拆分字符串。

如果您反转该模式,则会考虑: ,因为它是第一选择:

>>> re.split(':|\s*', 'find  a str:s2')
['find', 'a', 'str', 's2']

答案 1 :(得分:-4)

如果您打算做"或"为了你的匹配,那么你必须做这样的事情: re.split('(\s*|:)', 'find a str:s2') 简而言之: " +"意味着"至少一个角色"。 " *"任何(或没有)