Python中的正则表达式 - 使用组

Che*_*het 6 python regex pattern-matching

我是regex的新手,为什么这不输出'present'?

tale = "It was the best of times, ... far like the present ... of comparison only. "
a = re.compile('p(resent)')
print a.findall(tale)

>>>>['resent']
Run Code Online (Sandbox Code Playgroud)

Bar*_*mar 1

来自Python文档

如果模式中存在一个或多个组,则返回组列表

如果您希望它仅使用组进行分组,而不使用捕获组,请使用非捕获组:

a = re.compile('p(?:resent)')
Run Code Online (Sandbox Code Playgroud)

对于这个正则表达式来说,它没有意义,但对于更复杂的正则表达式来说它可能是合适的,例如:

a = re.compile('p(?:resent|eople)')
Run Code Online (Sandbox Code Playgroud)

将匹配“present”或“people”。