python爬虫(七)-------------------正则re模块

import re

m = re.match(r'\d{3}\-\d{3,8}', '010-12345')
# print(dir(m))
print(m.string)#打印匹配到的结果
print(m.pos, m.endpos)
'''
参考:
	https://www.cnblogs.com/tina-python/p/5508402.html
注:match和search一旦匹配成功,就是一个match object对象,而match object对象有以下方法:

group() 返回被 RE 匹配的字符串#参数代表正则表达式中的括号的位置
start() 返回匹配开始的位置
end() 返回匹配结束的位置
span() 返回一个元组包含匹配 (开始,结束) 的位置
group() 返回re整体匹配的字符串,可以一次输入多个组号,对应组号匹配的字符串。
'''

# 分组
m = re.match(r'^(\d{3})-(\d{3,8})$', '010-12345')#有两个括号
#与re.search()的区别
'''
m.groups():('010', '12345')
m.groups(0):010-12345
m.groups(1):010--------------------(\d{3})
m.groups(2):12345-------------------(\d{3,8})

'''
print(m.groups())
print(m.group(0))
print(m.group(1))
print(m.group(2))
'''
re.match()方法与pattern.match()方法区别:
re.match()不能指定匹配的区间pos和endpos两个参数,pattern.match可以



pattern = re.compile(r'hello')
pattern.match('hello world!')
以上两句等价于re.match(r”hello”,”hello world!”)
即re不用compile函数也能match

参考:
	https://www.cnblogs.com/xiaxiaoxu/p/9749655.html
'''

# 分割
p = re.compile(r'\d+')
print(type(p))
print(p.split('one1two3three3four4'))
print(m.group(2))

t = '20:15:45'
#括号用来分组,
re.match(r'^(0[0-9]|1[0-9]|2[0-3]|[0-9])\:(0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]|[0-9])\:(0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]|[0-9])$', t)
#打印分组结果
print(m.groups())

猜你喜欢

转载自blog.csdn.net/qq_41228218/article/details/88969742