python中正则模块

import re

# 1. findall()  匹配字符串中所有符合正则的字符串,并返回一个列表
result_list = re.findall(r"\d+", "我的手机号是13812345678,我的QQ号是456789123")
print(result_list, type(result_list))  # ['13812345678', '456789123'] <class 'list'>
print("==============")

# 2. finditer()  匹配字符串中所有符合正则的字符串,并返回一个迭代器
result_iter = re.finditer(r"\d+", "我的手机号是13812345678,我的QQ号是456789123")
for match in result_iter:
    print(match, type(match))  # Match 对象  从Match对象中获取数据需要使用group()方法
    print(match.group())  # 13812345678 456789123

print("==============")
# 3. search()  匹配字符串中第一个符合正则的字符串,并返回一个Match对象
result_match = re.search(r"\d+", "我的手机号是13812345678,我的QQ号是456789123")
print(result_match.group(), type(result_match))  # Match 对象  <class 're.Match'>

print("==============")
# 4. match()  从头开始匹配,如果字符串开始位置匹配正则表达式,返回一个Match对象,否则返回None
# 可以认为在正则的前面加上了  ^
result_match = re.match(r"\d+", "我的手机号是13812345678,我的QQ号是456789123")
try:
    print(result_match.group(), type(result_match))  # 13812345678 <class 're.Match'>
except Exception:
    print("NoneType类型中没有group()方法")

print("================")
x = 'ascgfgadabcabfa123adc132'
# 5. sub()  替换,后面的count是指定替换的个数,sub是直接返回的新的字符串
r = re.sub(r'a\wc', 'xxxxx', x, count=1)
print(r, type(r))
print(x)
print("=========")

# 6. subn() 这个方法返回的是一个元组包含两个元素,第一个元素返回的是替换后新的字符串,第二个元素是替换的个数
r = re.subn(r'a\wc', 'xxxxx', 'ascgfgadabcabfa123adc132')
print(r, type(r))
print("===============")

# 7. split() 分割,将字符串将指定模式进行分割,返回的是一个列表
# 如果字符串最开始就可以匹配到指定的模式,则返回列表的第一个元素为空
# 如果字符串最尾部可以匹配到指定的模式,则返回列表的最后一个元素为空
r = re.split(r'a\wc', 'ascgfgadabcabfa123adc132')
print(r, type(r))
print("==========")

# 8. 预加载正则表达式
obj = re.compile(r"\d+")
result_iter = obj.finditer("我的手机号是13812345678,我的QQ号是456789123")
for match in result_iter:
    print(match.group())  # 13812345678 456789123

print("================")
# 9. 惰性匹配
s = """
<div class='jay'><span id='1'>抽烟</span></div>
<div class='jj'><span id='2'>喝酒</span></div>
<div class='jolin'><span id='3'>烫头</span></div>
<div class='sylar'><span id='4'>阿巴阿巴</span></div>
<div class='tory'><span id='5'>???</span></div>
"""

obj = re.compile(r"<div class='.*?'><span id='(?P<id>.*?)'>(?P<content>.*?)</span></div>", re.S)
result_iter = obj.finditer(s)
for match in result_iter:
    print(match.group(2))  # 抽烟 喝酒 烫头 阿巴阿巴 ???
    print(match.group("id"))

    # 构建为字典的格式
    print(match.groupdict())


posted @   愿风带走思绪  阅读(5)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示