6

I am new to regex, why does this not output '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']
4

2 回答 2

3

try something like this if you're trying to match the exact word present here:

In [297]: tale="resent present ppresent presentt"

In [298]: re.findall(r"\bpresent\b",tale)
Out[298]: ['present']
于 2012-12-25T03:01:42.520 回答
1

来自Python 文档

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

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

a = re.compile('p(?:resent)')

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

a = re.compile('p(?:resent|eople)')

将匹配 'present' 或 'people'。

于 2012-12-25T03:06:34.370 回答