zoukankan      html  css  js  c++  java
  • python正则-group()

    最近要开始系统的学习一遍python的正则表达式,所以笔记还是要记起来滴。

    python利用正则表达式匹配到的字符串,可以通过group()方法获取。

    group()/group(0)

    group(num)

    groups()

    举个栗子:

    #!/usr/bin/python3
    import re

    line = "Cats are smarter than dogs"

    matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)

    if matchObj:
    print ("matchObj.group() : ", matchObj.group())
    print ("matchObj.group(0) : ", matchObj.group(0))
    print ("matchObj.group(1) : ", matchObj.group(1))
    print ("matchObj.group(2) : ", matchObj.group(2))
    print ("matchObj.groups() : ", matchObj.groups())
    else:
    print ("No match!!")

    执行结果:

    >>>
    ('matchObj.group() : ', 'Cats are smarter than dogs')
    ('matchObj.group(0) : ', 'Cats are smarter than dogs')
    ('matchObj.group(1) : ', 'Cats')
    ('matchObj.group(2) : ', 'smarter')
    ('matchObj.groups() : ', ('Cats', 'smarter'))
    >>>

    由以上栗子可以得出关于group()各种使用方式的区别:

    group()和group(0)效果一样,用于获取正则表达式匹配到的全部结果,参数默认0;

    group(num),num为正整数,获取正则表达式匹配结果中相应的第n个括号内的元组;

    groups(),用于获取正则表达式全部括号内的元组。

    如果正则中没有用到括号,那么group()使用会报错:

    Traceback (most recent call last):
    File "<pyshell#9>", line 1, in <module>
    s.groups().get()
    AttributeError: 'NoneType' object has no attribute 'groups'

  • 相关阅读:
    与众不同 windows phone (39)
    与众不同 windows phone (38)
    与众不同 windows phone (37)
    与众不同 windows phone (36)
    与众不同 windows phone (35)
    与众不同 windows phone (34)
    重新想象 Windows 8 Store Apps 系列文章索引
    重新想象 Windows 8 Store Apps (71)
    重新想象 Windows 8 Store Apps (70)
    重新想象 Windows 8 Store Apps (69)
  • 原文地址:https://www.cnblogs.com/littlebird1/p/8424102.html
Copyright © 2011-2022 走看看