python正则--group

正则匹配方法:
re.match函数
re.match 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match() 就返回 none
re.search方法
re.search 扫描整个字符串并返回第一个成功的匹配

group作用:
python正则中,用group函数来定位括号表达式匹配到的结果中特定的字段,你可以理解为索引,有n个括号表达式group里面的索引最大值就是n,group(k)就代表第k个括号表达式匹配到的结果

.* 代表匹配除换行符之外的所有字符
.*? 后面多个问号,代表非贪婪模式,也就是说只匹配符合条件的最少字符

1.不使用括号表达式
那么只能使用group()/group(0),打印出所有的匹配结果,而不能使用group(k)

import re

line = "some cats are smarter than dogs are true"
mat1 = re.match(r".* are", line)
mat2 = re.match(r".*? are", line)

print(mat1)
print(mat2)
print(mat1.group(0))
# <re.Match object; span=(0, 35), match='some cats are smarter than dogs are'>
# <re.Match object; span=(0, 13), match='some cats are'>
# some cats are smarter than dogs are

加上索引则会报错:

print(mat1.group(1))
# IndexError: no such group

直接使用groups()则会得到一个空的元组

import re

line = "some cats are smarter than dogs are true"
mat1 = re.match(r".* are", line)
print(mat1.groups())
# ()

2.使用括号表达式
根据索引获取匹配结果:

import re

line = "some cats are smarter than dogs are true"
mat1 = re.match(r"(.*) are", line)
mat2 = re.match(r"(.*?) are .* dogs (.*)", line)

print(mat1.group(1))
print(mat2)
print(mat2.group(1))
print(mat2.group(2))


# some cats are smarter than dogs
# <re.Match object; span=(0, 40), match='some cats are smarter than dogs are true'>
# some cats
# are true

group()一次可以跟多个索引,会生成一个元组

print(type(mat2.group(2, 1)))
# ('are true', 'some cats')
# <class 'tuple'>

groups()则是把所有的group()生成一个元组

print(mat2.groups())
print(type(mat2.groups()))

# ('some cats', 'are true')
# <class 'tuple'>

使用group(0)/group()则会返回包含括号表达式的所有正则匹配

import re

x = "abaxxaa123123asa12143"
t = re.match('[a-zA-Z]+(\d+?)[a-z]+(\d+?)', x)
print(t)
print(t.group(0))
print(t.group())
print(t.groups())
print(t.group(2))

输出为:

<re.Match object; span=(0, 17), match='abaxxaa123123asa1'>
abaxxaa123123asa1
abaxxaa123123asa1
('123123', '1')
1
  • 4
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值