python正则表达式re.group()怎么使用(python,开发技术)

时间:2024-05-05 14:58:34 作者 : 石家庄SEO 分类 : 开发技术
  • TAG :

    python%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8Fre.group%28%29%E6%80%8E%E4%B9%88%E4%BD%BF%E7%94%A8

在正则表达式中,re.group()方法是用来提取出分组截获的字符串,匹配模式里的括号用于分组。

举例说明:

importre

ifname=='main':

test_pattern=r"(\d{2}年)(\d{4}年)(\d{4}年)"

test="18年2023年2020年"

print(re.search(test_pattern,test).group())

print(re.search(test_pattern,test).group(0))

print(re.search(test_pattern,test).group(1))

print(re.search(test_pattern,test).group(2))

print(re.search(test_pattern,test).group(3))

输出:

18年2023年2020年
18年2023年2020年
18年
2023年
2020年

Process finished with exit code 0

匹配模式中的三个括号将匹配结果分成了三组。

re.group() 与re.group(0)就是匹配的整体结果;

re.group(1) 列出第一个括号匹配部分;

re.group(2) 列出第二个括号匹配部分;

re.group(3) 列出第三个括号匹配部分。

注意,如果没有匹配成功的,re.search返回的结果是None,使用group()会报错,如下所示:

AttributeError: 'NoneType' object has no attribute 'group'

如果匹配模式中没有括号(分组),使用group(1)、group(2)、group(3)会报错,如下所示:

IndexError: no such group

本文:python正则表达式re.group()怎么使用的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:Python怎么使用random.shuffle()随机打乱字典排序下一篇:

38 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18