# -*- coding: utf-8 -*-
# @Date : 2018-10-30
# @Author : Peng Shiyu
# re 模块正则表达式处理字符串
# re 默认会保存编译后的匹配模式
import re
# match 匹配
def match_func():
text = "2018/11/1"
ret = re.match("(\d{4})/(\d{1,2})/(\d{1,2})", text)
# group 抽取匹配的字符串
if ret is not None:
print(ret.group())
print(ret.group(0, 1, 2, 3))
print(ret.groups())
year, month, day = ret.groups()
print(year)
print(month)
print(day)
"""
2018/11/1
('2018/11/1', '2018', '11', '1')
('2018', '11', '1')
2018
11
1
"""
# search 搜索
def search_func():
text = "the day is 2018/11/1"
ret = re.search("(\d{4})/(\d{1,2})/(\d{1,2})", text)
if ret:
year, month, day = ret.groups()
print(year)
print(month)
print(day)
"""
2018
11
1
"""
# sub 替换
def sub_func():
text = "day day up"
print(text.replace("up", "good")) # 更快
ret = re.sub("[au]", "=", text)
print(ret)
# findall 查找所有
def findall_func():
text = "2018, 2009, 20, 2005"
ret = re.findall("\d{4}", text)
print(ret) # <class 'list'>
# ['2018', '2009', '2005']