我刚接触正则表达式,为什么这个代码无法输出“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']
我刚接触正则表达式,为什么这个代码无法输出“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']
如果你想精确匹配单词present
,可以尝试以下方法:
In [297]: tale="resent present ppresent presentt"
In [298]: re.findall(r"\bpresent\b",tale)
Out[298]: ['present']
来自Python文档
如果模式中存在一个或多个组,则返回一个组列表
如果您只想使用组进行分组,而不是捕获,请使用非捕获组:
a = re.compile('p(?:resent)')
对于这个正则表达式,没有实际意义,但是对于更复杂的正则表达式,例如:
a = re.compile('p(?:resent|eople)')
将匹配'present'或'people'。
(\d+)%
。 - Barmarre.findall
时,如果没有找到括号,则整个字符串将成为结果元素。当使用search
或match
时,您可以通过使用result.group(0)
指定整个字符串或使用result.group(1)
等访问组。 - Anorova = re.compile('(p(resent))')
? - Blue Magister['present', 'resent']
。 - Barmar
'resent'
。你能提供一个更好的输入/输出示例吗? - Ashwini Chaudharytale="resent present ppresent presentt"
? - Ashwini Chaudhary