简体   繁体   English

为什么有关“ *”模式的简单正则表达式不起作用?

[英]why the simple regex about “*” pattern does not work?

the code is following 代码如下

str="baaaacbd"
pattern = re.compile(r"a*")
mat = pattern.search(str)
print mat.group()

the output is nothing! 输出什么都没有! it is disturbing! 令人不安! Why? 为什么?

First off, don't use python built-in type names as your variable names. 首先,不要使用python内置类型名称作为变量名称。 Secondly, a* means match 0 or more of character a and re.search() will return the first occurrence of the pattern which is 0 occurrence. 其次, a*表示匹配字符a 0个或多个,并且re.search()将返回模式的第一个匹配项,即0个匹配项。 You can use groups() to see all the matches: 您可以使用groups()查看所有匹配项:

In [34]: pattern = re.compile(r"(a*)")

In [35]: mat = pattern.search(s)

In [36]: print(mat.group())

In [37]: print(mat.groups())
('',)

Or use a+ to match 1 or more character, which in this case is what you want: 或使用a+匹配1个或多个字符,在这种情况下,这就是您想要的:

In [38]: pattern = re.compile(r"a+")

In [39]: mat = pattern.search(s)

In [41]: print(mat.group())
aaaa

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM