带*的python正则表达式不匹配

2024-06-26 13:19:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习python。我使用的是python3.6

reObject = re.compile(r'(ab*)')
mo1 = reObject.search('My name is abbb')
print (mo1.group())

上面的代码只匹配'name'中的a,而不是abbb

但是下面的代码匹配得很好。在

^{pr2}$

如果字母表出现在搜索的字符串之前,如何匹配字符串?在


Tags: 字符串代码nameresearchabismy
2条回答

Regular Expression Syntax。在

* Causes the resulting RE to match 0 or more repetitions of the preceding RE, as many repetitions as are possible. ab* will match ‘a’, ‘ab’, or ‘a’ followed by any number of ‘b’s.

+ Causes the resulting RE to match 1 or more repetitions of the preceding RE. ab+ will match ‘a’ followed by any non-zero number of ‘b’s; it will not match just ‘a’.

如果您担心为什么ab*只匹配第一个a,那么从技术上讲它不匹配。问题在于您如何使用模式: ^{}只扫描第一个匹配项。如果要查找所有匹配项,请查看^{}。在

http://www.rexegg.com/regex-quickstart.html是正则表达式的一个很好的资源

*字符表示查找0或更多 这将找到a和0 b

+字符表示查找1个或多个

所以(ab+)会找到abbb

相关问题 更多 >