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
本文详细介绍了Python中正则表达式的捕获组概念,包括普通捕获组和命名捕获组的使用。通过示例展示了如何通过捕获组匹配和提取字符串中的特定部分,便于后续处理。普通捕获组按括号出现顺序编号,而命名捕获组则可通过名称引用,使得代码更具可读性。
-- 捕获组 (capture group)&spm=1001.2101.3001.5002&articleId=124664191&d=1&t=3&u=d1871b4aef37424a820000f9795b3843)
1173

被折叠的 条评论
为什么被折叠?



