Python--re模块

正则表达式

Python笔记 之 正则表达式

模式
  • A 默认模式
  • I 忽略大小写
  • L 本地化识别匹配
  • M 多行匹配
  • S 使"."匹配包括换行在内的所有字符
  • X 忽略空白和注释,以便更易理解。
  • U 使用Unicode字符集解析字符
函数
string = 'Ana Lee,New york,female,1978-12-22,ana@126.com'  
email = '\w{3,20}@126.com|163.com'
  • compile
    compile(pattern, flags=0)
    将一个正则表达式生成为一个匹配对象
    例:
com = re.compile(email,flags=re.U)  
print(com)
#result
re.compile('\\w{3,20}@126.com|163.com')
  • match
    match(pattern, string, flags=0)
    从字符串的开始位置起匹配正则表达式
print(com.match(string[-11:])) 
#result
<re.Match object; span=(0, 11), match='ana@126.com'>
print(re.match(com,string))
#result
None
  • fullmatch
    fullmatch(pattern, string, flags=0)
    将正则表达式与字符串的所有部分匹配
print(com.fullmatch(string[-11:])) 
#result
<re.Match object; span=(0, 11), match='ana@126.com'>
print(re.fullmatch(com,string))
#result
None
  • search
    search(pattern, string, flags=0)
    在字符串中搜索正则表达式第一次匹配上的位置
print(com.search(string))
#或者写作
print(re.search(com,string))
#result
<re.Match object; span=(35, 46), match='ana@126.com'>
  • sub
    sub(pattern, repl, string, count=0, flags=0)
    用字符串替代原字符串中所有匹配上正则表达式的子串
print(com.sub('Ana@163.com',string))
#或者写作
print(re.sub(com,'Ana@163.com',string)) 
#result
Ana Lee,New york,female,1978-12-22,Ana@163.com
  • subn
    subn(pattern, repl, string, count=0, flags=0)
    同sub,并返回替换的数量
print(com.subn('Ana@163.com',string))
#或者写作
print(re.subn(com,'Ana@163.com',string))
#result
('Ana Lee,New york,female,1978-12-22,Ana@163.com', 1)
  • split
    split(pattern, string, maxsplit=0, flags=0)
    将字符串按照正则表达式匹配结果进行分割
print(com.split(string))
#或者写作
print(re.split(com,string))  
#result
['Ana Lee,New york,female,1978-12-22,', '']
  • findall
    findall(pattern, string, flags=0)
    在字符串中搜索并返回所有匹配的结果
print(com.findall(string))
#或者写作
print(re.findall(com,string))  
#result
['ana@126.com']
  • finditer
    finditer(pattern, string, flags=0)
    搜索字符串,返回匹配结果的迭代器
print(com.finditer(string).__next__())  
#或者 
print(next(re.finditer(com,string)))
#result
<re.Match object; span=(35, 46), match='ana@126.com'>
  • purge
    purge()
    清除清除正则表达式缓存
    re.purge())
  • escape
    escape(pattern)
    转义字符串中的特殊字符。
print(re.escape(email))
#result
\\w\{3,20\}@126\.com\|163\.com
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值