Python模块之re
re模块 准备:
flags有很多可选值: re.I(IGNORECASE)忽略大小写,括号内是完整的写法
re.M(MULTILINE)多行模式,改变^和$的行为
re.S(DOTALL)点可以匹配任意字符,包括换行符
re.L(LOCALE)做本地化识别的匹配,表示特殊字符集 \w, \W, \b, \B, \s, \S 依赖于当前环境,不推荐使用
re.U(UNICODE) 使用\w \W \s \S \d \D使用取决于unicode定义的字符属性。在python3中默认使用该flag
re.X(VERBOSE)冗长模式,该模式下pattern字符串可以是多行的,忽略空白字符,并可以添加注释 1)匹配方法 findall() search() mathc()
(1)findall()
def findall(pattern, string, flags=0):
"""Return a list of all non-overlapping matches in the string. If one or more capturing groups are present in the pattern, return
a list of groups; this will be a list of tuples if the pattern
has more than one group. Empty matches are included in the result."""
return _compile(pattern, flags).findall(string) 用法:所有的匹配结果都返回在一个列表中,如果没有匹配上就返回一个空列表。 例子:
import re
res = re.findall(r'\w+', r'Jake@tom')
print(res)
结果:
['Jake', 'tom'] (2)search()
def search(pattern, string, flags=0):
"""Scan through string looking for a match to the pattern, returning
a match object, or None if no match was found."""
return _compile(pattern, flags).search(string) 用法:返回第一个匹配到的对象,可以调用这个对象的 group()方法返回第一个匹配到的值。没有匹配上返回None。 例子:
import re
res1 = re.search(r'\d+', r'222T333')
print('search', res1)
print(res1.group())
结果:
search <_sre.SRE_Match object; span=(0, 3), match=''>
222 (3)match()
def match(pattern, string, flags=0):
"""Try to apply the pattern at the start of the string, returning
a match object, or None if no match was found."""
return _compile(pattern, flags).match(string) 用法:和search用法一样,唯一区别就是只在字符串开始匹配 例子:
import re
res2 = re.match(r'\d+', r'222T333')#与search区别就是只在字符串开始匹配
print('match', res2)
print(res2.group())
结果:
match <_sre.SRE_Match object; span=(0, 3), match=''>
222 2)切割和替换 sub() subn() split()
(1)sub()
def sub(pattern, repl, string, count=0, flags=0):
"""Return the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in string by the
replacement repl. repl can be either a string or a callable;
if a string, backslash escapes in it are processed. If it is
a callable, it's passed the match object and must return
a replacement string to be used."""
return _compile(pattern, flags).sub(repl, string, count) 用法:根据(pattern)正则表达式规则将匹配好的字符串替换为新字符串(repl),string为目标串,count可以指定替换次数 例子:
import re
res = re.sub(r'\d+', 'SSS',r'222XXX333V3')
print(res)
结果:
SSSXXXSSSVSSS (2)subn()
def subn(pattern, repl, string, count=0, flags=0):
"""Return a 2-tuple containing (new_string, number).
new_string is the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in the source
string by the replacement repl. number is the number of
substitutions that were made. repl can be either a string or a
callable; if a string, backslash escapes in it are processed.
If it is a callable, it's passed the match object and must
return a replacement string to be used."""
return _compile(pattern, flags).subn(repl, string, count) 用法:根据(pattern)正则表达式规则将匹配好的字符串替换为新字符串(repl),string为目标串,count可以指定替换次数.
返回的结果是元组,其中有替换结果和替换次数 例子:
import re
res = re.subn(r'\d+', 'SSS',r'222XXX333V3')
print(res)
结果:
('SSSXXXSSSVSSS', 3) (3)split()
def split(pattern, string, maxsplit=0, flags=0):
"""Split the source string by the occurrences of the pattern,
returning a list containing the resulting substrings. If
capturing parentheses are used in pattern, then the text of all
groups in the pattern are also returned as part of the resulting
list. If maxsplit is nonzero, at most maxsplit splits occur,
and the remainder of the string is returned as the final element
of the list."""
return _compile(pattern, flags).split(string, maxsplit) 用法:按照正则表达式匹配好的字符串去切割目标字符串,匹配对个结果会先拿第一个结果切割目标串,
切割完后拿第二个结果切割这两个字符串,以此类推。可以指定最大切割次数,返回一个列表。 例子:
import re
res = re.split(r'\d+', r'333FF444FF44')
print(res)
结果:
['', 'FF', 'FF', ''] 3)进阶 compile() finditer()
(1)compile()*****时间效率
def compile(pattern, flags=0):
"Compile a regular expression pattern, returning a pattern object."
return _compile(pattern, flags) 用法:把正则表达式编译为正则表达式对象
作用:节省时间,只有在多次使用某一个相同的正则表达式的时候,才会帮助我们提高效率。 例子:
import re
res = re.compile(r'\d+')
print(res)
结果:
re.compile('\\d+') (2)finditer()*****空间效率
def finditer(pattern, string, flags=0):
"""Return an iterator over all non-overlapping matches in the
string. For each match, the iterator returns a match object. Empty matches are included in the result."""
return _compile(pattern, flags).finditer(string) 用法:根据正则表达式匹配字符串得到 一个迭代器,迭代器中每个元素都是一个对象,每个
对象都可通过 group()方法获取对应的匹配值。 例子:
import re
res = re.compile(r'\d+')
res = re.finditer(r'\d+', r'sss444ff333f')
print(res)
for r in res:
print(r, '--------', r.group()) 结果:
<callable_iterator object at 0x106f29668>
<_sre.SRE_Match object; span=(3, 6), match=''> -------- 444
<_sre.SRE_Match object; span=(8, 11), match=''> -------- 333 3.正则表式进阶(很重要)
分组与re模块的组合使用
1)分组 () 与 findall() finditer()
import re
#findall会优先显示分组中的内容,如果在第左半边括号后加上?:就会取消分组优先
#(?:正则表达式) 取消优先
#如果有一个分组,那么就将匹配好的元素放到一个列表中,如果分组有两个以上,那么这些元组组成一个元组存到列表中
res = re.findall(r'<(\w+)>', r'<a>我爱你中国</a><h1>亲爱的母亲</h1>')
print(res)
res = re.findall(r'<(?:\w+)>', r'<a>我爱你中国</a><h1>亲爱的母亲</h1>')
print(res)
结果:
['a', 'h1']
['<a>', '<h1>'] #不会优先分组中内容,可以通过group(分组名)来得到分组中的值
import re
res = re.finditer(r'<(?:\w+)>', r'<a>我爱你中国</a><h1>亲爱的母亲</h1>')
for i in res:
print(i.group()) 结果:
<a>
<h1> 2)分组命名 分组与 search()
#(?P<name>正则表达式)表示给分组起名字
#(?P=name)表示使用这个分组,这里匹配到的内容应该和分组中内容完全一致
<1>
import re
#search匹配的是第一次匹配好的值
#得到的结果可以使用结果.group()方法得到
#如果search与分组配合使用给group传参数,第一个分组内容传1的到第一分组内容,以此类推
#groups()函数的到一个所有分组的集合以元组形式返回
res = re.search(r'<(\w+)>(\w+)</(\w+)>', r'<a>hello</a>')
print(res.group())
print(res.group(1))
print(res.group(2))
print(res.group(3))
print(res.groups())
结果:
<a>hello</a>
a
hello
a
('a', 'hello', 'a') <2>
import re
res = re.search(r'<(?P<name>\w+)>\w+</(?P=name)>', r'<a>hello</a>')
print(res.group('name'))
print(res.group()) res = re.search(r'<(?P<name>\w+)>\w+</(?P=name)>', r'<a>hello</h1><a>hello</a>')
print(res.group('name')) 结果:
a
<a>hello</a>
a <3>
import re res = re.search(r'<(?P<tt>\w+)>(?P<cc>\w+)</\w+>', r'<a>hello</h1><a>hello</a>')
print(res.group('tt'))
print(res.group('cc'))
print(res.group()) 结果:
a
hello
<a>hello</h1> 3)通过索引使用分组
#\1表示使用第一组,匹配到的内容必须和第一组中的内容完全一致。
import re
#\1表示使用第一组,匹配到的内容必须和第一组中的内容完全一致。
res = re.search(r'<(\w+)>\w+</\1>', r'<a>hello</a>')
print(res.group(1))
print(res.group())
结果:
a
<a>hello</a> 4)分组与 split()
切割后的结果会保留分组内被切割的内容
import re
ret = re.split('(\d+)','Tom18Jake20Json22')
print(ret) 结果:
['Tom', '', 'Jake', '', 'Json', '', ''] 总结:
# 在python中使用正则表达式
# 转义符 : 在正则中的转义符 \ 在python中的转义符
# re模块
# findall search match
# sub subn split
# compile finditer
# python中的正则表达式
# findall 会优先显示分组中的内容,要想取消分组优先,(?:正则表达式)
# split 遇到分组 会保留分组内被切掉的内容
# search 如果search中有分组的话,通过group(n)就能够拿到group中的匹配的内容
# 正则表达式进阶
# 分组命名
# (?P<name>正则表达式) 表示给分组起名字
# (?P=name)表示使用这个分组,这里匹配到的内容应该和分组中的内容完全相同
# 通过索引使用分组
# \1 表示使用第一组,匹配到的内容必须和第一个组中的内容完全相同
Python模块之re的更多相关文章
- 使用C/C++写Python模块
最近看开源项目时学习了一下用C/C++写python模块,顺便把学习进行一下总结,废话少说直接开始: 环境:windows.python2.78.VS2010或MingW 1 创建VC工程 (1) 打 ...
- Python模块之configpraser
Python模块之configpraser 一. configpraser简介 用于处理特定格式的文件,其本质还是利用open来操作文件. 配置文件的格式: 使用"[]"内包含 ...
- Python模块之"prettytable"
Python模块之"prettytable" 摘要: Python通过prettytable模块可以将输出内容如表格方式整齐的输出.(对于用Python操作数据库会经常用到) 1. ...
- python 学习第五天,python模块
一,Python的模块导入 1,在写python的模块导入之前,先来讲一些Python中的概念性的问题 (1)模块:用来从逻辑上组织Python代码(变量,函数,类,逻辑:实现一个功能),本质是.py ...
- windows下安装python模块
如何在windows下安装python模块 1. 官网下载安装包,比如(pip : https://pypi.python.org/pypi/pip#downloads) pip-9.0.1.tar. ...
- 安装第三方Python模块,增加InfoPi的健壮性
这3个第三方Python模块是可选的,不安装的话InfoPi也可以运行. 但是如果安装了,会增加InfoPi的健壮性. 目录 1.cchardet 自动检测文本编码 2.lxml 用于解析 ...
- Python基础篇【第5篇】: Python模块基础(一)
模块 简介 在计算机程序的开发过程中,随着程序代码越写越多,在一个文件里代码就会越来越长,越来越不容易维护. 为了编写可维护的代码,我们把很多函数分组,分别放到不同的文件里,这样,每个文件包含的代码就 ...
- python 模块加载
python 模块加载 本文主要介绍python模块加载的过程. module的组成 所有的module都是由对象和对象之间的关系组成. type和object python中所有的东西都是对象,分为 ...
- pycharm安装python模块
这个工具真的好好,真的很喜欢,它很方便,很漂亮,各种好 pycharm安装python模块:file-setting-搜索project inte OK
- Python模块常用的几种安装方式
Python模块安装方法 一.方法1: 单文件模块直接把文件拷贝到 $python_dir/Lib 二.方法2: 多文件模块,带setup.py 下载模块包,进行解压,进入模块文件夹,执行:pytho ...
随机推荐
- laravel基础课程---13、数据库基本操作2(lavarel数据库操作和tp对比)
laravel基础课程---13.数据库基本操作2(lavarel数据库操作和tp对比) 一.总结 一句话总结: 非常非常接近:也是分为两大类,原生SQL 和 数据库链式操作 学习方法:使用时 多看手 ...
- ctypes模块与pywin32模块
ctypes模块: 主要用于调用c动态链接库. 1.聊聊Python ctypes模块 2.ctypes模块管理 相关网址: pywin32模块: 用于访问win32API函数(win32api模块) ...
- Android Studio的技巧
1.快速添加add unimplements methods: 右键generate 2.快速添加try-catch:左边就有一个小电灯,然后可以选. 3.格式化OPTION + CMD + L ( ...
- Gym-101673: A Abstract Art (模板,求多个多边形的面积并)
手抄码板大法. #include<bits/stdc++.h> using namespace std; #define mp make_pair typedef long long ll ...
- 【C++基础】重载,覆盖,隐藏
函数签名的概念 函数签名主要包括1.函数名:2.参数列表(参数的个数.数据类型和顺序):但是注意,C++官方定义中函数签名不包括返回值!! 1.重载 函数重载是指在同一作用域内,可以有一组具有相同函数 ...
- Django 模板 自定义context_processors
Django版本 1.8.4 为什么要自定义context_processors 在做博客的过程中,在浏览排行,评论排行,标签,文章归档,友情链接等内容每一个显示页面都是要显示的.如果在每一个view ...
- window系统的HOST详解
很多用户都知道在Window系统中有个Hosts文件(没有后缀名),在Windows 98系统下该文件在Windows目录,在Windows 2000/XP系统中位于C\Winnt\System32 ...
- bzoj 5281 [Usaco2018 Open]Talent Show——0/1分数规划
题目:https://www.lydsy.com/JudgeOnline/problem.php?id=5281 把分子乘1000,就能在整数里做了. 这种水题也花了这么久…… #include< ...
- wxPython学习资料
[译]wxPython布局管理简介 https://www.pystack.org/wxpython_sizer/ 设计器.代码分离 http://book.douban.com/review/578 ...
- WPF TreeView 后台C#选中指定的Item, 需要遍历
private TreeViewItem FindTreeViewItem(ItemsControl container, object item) { ...