Python正则模块

re模块

import re

# match
# 从头开始匹配, 只匹配一次,就结束
a = re.match('\d+', '54:58天5488:8451')   # 默认就是0个群组
print(a.group())                # 54

a = re.match('(\d+):(\d+)', '54:58天5488:8451')   # 返回一个匹配对象
print(a)                        # <_sre.SRE_Match object; span=(0, 5), match='54:58'>
print(a.group())                # 54:58
print(a.group(0))               # 54:58
print(a.group(1))               # 54
print(a.group(2))               # 58


# search
# 任意位置匹配,只要匹配到了一个,就结束
b = re.search('(\d+):(\d+)', '你好54:845Niha2212:5454')
print(b)                  # <_sre.SRE_Match object; span=(2, 8), match='54:845'>
print(b.group())          # 54:845
print(b.group(0))         # 54:845
print(b.group(1))         # 54
print(b.group(2))         # 845

# findall
# 匹配满足条件的全部内容,返回一个列表
c = re.findall('\d+', 'Niahhod5451:854jijdif8888:451nihao888')
print(c)      # ['5451', '854', '8888', '451', '888']

c = re.findall('(\d+):(\d+)', 'Niahhod5451:854jijdif8888:451nihao888')
print(c)      # [('5451', '854'), ('8888', '451')]

c = re.findall('\d+:\d+', 'Niahhod5451:854jijdif8888:451')
print(c)      # ['5451:854', '8888:451']
posted @ 2017-10-09 20:14  cnkai  阅读(366)  评论(0编辑  收藏  举报