在学习正则表达式的时候关于()和?:的内容一直不怎么理解,虽然能够明白使用$n来访问存储的内容,但对于它的使用也只限于教材中正则表达式的学习,但并没有明确的概念怎么使用。
在python中,re.match的返回值对象,是可以通过group方法来访问正则表达式中()的内容的。同样也是可以通过?:来控制不对()中的内容进行保存的,这样,在group方法中就不会访问到它。
import re
line = 'Cats are smarter than dogs'
match_obj = re.match('(.*) are (.*?) (?:.*)', line, re.M|re.I)
if match_obj:
print('match_obj.group(): ', match_obj.group())
print('match_obj.group(1): ', match_obj.group(1))
print('match_obj.group(2): ', match_obj.group(2))
print('match_obj.group(3): ', match_obj.group(3))
else:
print('No match!')
这样虽然有三个(),但实际访问只有2个内容,第三项会报出Exception has occurred: IndexError的异常信息