我是 python 的新手,正在练习 google python exercies 中的一些正则表达式 那里的一部分说:
Repetition
Things get more interesting when you use
+and*to specify repetition in the pattern
+-- 1 or more occurrences of the pattern to its left, e.g.i+= one or morei's
*-- 0 or more occurrences of the pattern to its left
所以我决定尝试一些 sample 。
import re
text="xx1 2 3xx"
match = re.search(r'\d\s+\d\s+\d',text)
match.group()
这会产生以下输出:
1 2 3
为了理解 * 和 + 之间的区别,我尝试了这个:
import re
text="xx1 2 3xx"
match = re.search(r'\d\s*\d\s*\d',text)
match.group()
并产生了输出:
1 2 3
(与输出1相同)
我还是想知道,* 和 + 是否真的有相同的功能?如果没有示例,我们将不胜感激!
如有不妥之处请指正
请您参考如下方法:
就像它说的那样,* 匹配零个或多个,+ 匹配一个或多个。但是您只在有多个空格的情况下测试了它们,这意味着它们都适用。比较您的正则表达式在 "xx12 3xx" 上的工作方式,其中前两位数字之间有 0 个空格。
