group分组

import re

s = 'life is short, I use python, I love python'

# 提取life和python直接的字符串
# 定界:普通字符会起到定界的作用
r = re.search('life.*python',s)  #\w不能匹配空格,所以这里必须要用.
print(r.group()) #life is short, I use python, I love python

# 只要 is short, I use , 爬虫基础
r = re.search('life(.*)python(.*)python',s) 
# group(0)永远返回的是字符串完整的匹配结果,0也可以省略group()
print(r.group(0)) # life is short, I use python, I love python
print(r.group(1)) #  is short, I use 
print(r.group(2)) # , I love 
print(r.groups()) #(' is short, I use ', ', I love ')
# 推荐使用findall
r = re.findall('life(.*)python(.*)python',s)
print(r) # [(' is short, I use ', ', I love ')]
# 'list' object has no attribute 'groups'

results matching ""

    No results matching ""