正则表达式(Regex)-- 捕获组 (capture group)

Regular Expression HOWTO — Python 3.10.4 documentation

捕获组就是把正则表达式中子表达式匹配的内容,保存到内存中以数字编号或显式命名的组里,方便后面引用。
分为普通捕获组(Expression) 和 命名捕获组(?<name>Expression) 。

普通捕获组:

如果没有显式为捕获组命名,即没有使用命名捕获组,那么需要按数字顺序来访问所有捕获组。在只有普通捕获组的情况下,捕获组的编号是按照“(”出现的顺序,从左到右,从1开始进行编号的 。

import re

year_pattern = re.compile((\d{4})-(\d{2}-(\d\d)))
test_str = '2022-05-09'
match = version_pattern.search(test_str)
print(match.group(0)) #2022-05-09
print(match.group(1)) #2022      
print(match.group(2)) #05-09     
print(match.group(3)) #09
     

命名捕获组

import re

version_pattern = re.compile(r'.*?Test *?Suite *(?P<major>[0-9\.]+)_(sts-)?[rR]?(?P<minor>[0-9\-]+) \(P?\d')
test_str = 'Android Security Test Suite 12_sts-r2 (8385251)\n'
match = version_pattern.search(test_str)
major_version = match.groupdict().get(u'major') #12
minor_version = match.groupdict().get(u'minor') #2

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值