python re模块中的“[ab]+'相等”(a | b)+吗?

2024-04-26 06:04:54 发布

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

我认为pat1='[ab]'和pat2='a | b'在python2.7,windows)“re”模块中具有与正则表达式模式相同的函数。但是我把“[ab]+”和“(a | b)+”混淆了,它们是否具有相同的功能,如果没有,你可以详细解释一下。在

'''
Created on 2012-9-4

@author: melo
'''

import re
pat1 = '(a|b)+'
pat2 = '[ab]+'
text = '22ababbbaa33aaa44b55bb66abaa77babab88'

m1 = re.search(pat1, text)
m2 = re.search(pat2, text)
print 'search with pat1:', m1.group()
print 'search with pat2:', m2.group()

m11 = re.split(pat1, text)
m22 = re.split(pat2, text)
print 'split with pat1:', m11
print 'split with pat2:', m22

m111 = re.findall(pat1, text)
m222 = re.findall(pat2, text)
print 'findall with pat1:', m111
print 'findall with pat2:', m222

输出如下:

^{pr2}$

拍2和拍1有什么区别? “pat1”实际上可以匹配什么类型的字符串?在


Tags: textresearchabwithgroupsplitprint
1条回答
网友
1楼 · 发布于 2024-04-26 06:04:54

在第一个模式中有一个捕获组。在

根据the docs

re.split()
... If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list. ...

尝试将组设为非捕获状态,然后查看您是否得到了预期的结果:

pat1 = '(?:a|b)+'

相关问题 更多 >