十七. Python基础(17)--正则表达式
十七. Python基础(17)--正则表达式
1 ● 正则表达式
定义: Regular expressions are sets of symbols that you can use to create searches for finding and replacing patterns of text. |
零宽断言(zero width assertion): 零宽断言--不是去匹配字符串文本,而是去匹配位置(开头, 结尾也是位置)。 常见的: ① 起始位置^(单行)和/A(多行), ② 末尾位置 $(单行)和/Z(多行) ③ 单词边界/b, 非单词边界/B等等。 ④ (?=exp): 匹配后面是exp的位置 (?!exp): 匹配后面不是exp的位置 (?<=exp): 匹配前面是exp的位置 (?<!exp): 匹配前面不是exp的位置 (?#exp): 表示括号内是注释
※ |
参考文章: ① 正则基础 http://www.cnblogs.com/Eva-J/articles/7228075.html#_label10 http://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html http://www.runoob.com/regexp/regexp-metachar.html ② 向后引用(回溯引用)以及零宽断言 http://www.cnblogs.com/linux-wangkun/p/5978462.html http://www.cnblogs.com/leezhxing/p/4333773.html |
2 ● 正则的难点示例
① \b匹配这样的位置: 简单来说: 单词边界(word boundary) 具体来说: 它的前一个字符和后一个字符不全是(一个是, 一个不是或不存在)\w. 例如: a!bc, 经过如下替换: 结果变成: !bc
② \B匹配这样的位置: 简单来说: 非单词边界(not word boundary) 例如: ab cd ef, 经过如下替换: 结果变成: aAAAb cAAAd eAAAf
③ abc ab,c
AaAbAcA AaAb,AcA
④ 匹配不包括逗号的行 abcd abcd, ,abcd ab,cd
^((?!,).)*$表示不包括逗号","的行 ^((?<!,).)*$不能表示不包括逗号的行, 因为会把"abc,"这种情况也错误匹配上 ※ ^((?![A-Za-z]).)*$
※ ^((?!^[0-9]).)*$
※ (?<!(^))'''或者(?<!^)'''
※ (?<=\()\S+(?=\))
⑤(?#expr) 2[0-4]\d(?#200-249)|25[0-5](?#250-255)|[01]?\d\d?(?#0-199)
⑥ 贪婪(greedy)与非贪婪(non-greedy) 贪婪—尽可能多地重复 非贪婪—尽可能少地重复 |
3 ● python反向引用(back-reference)
import re text = "Hello Arroz, Nihao Arroz" rep = re.sub(r"Hello (\w+), Nihao \1", "GOOD", text) # GOOD rep = re.sub(r"Hello (\w+), Nihao \1", "\g<1>", text) # Arroz rep = re.sub(r"Hello (\w+), Nihao \1", "\g<0>", text) # Hello Arroz, Nihao Arroz |
※ (...) matches whatever regular expression is inside the parentheses, and indicates the start and end of a group. ※ \g<N> 是用来反向引用(backreferences)的; 如果N是正数, 那么\g<N> 匹配(对应) 从左边数起,第N个括号里的内容; 例如上面的\g<1>匹配Arroz 如果N是0,那么\g<N> 匹配(对应) 整个字符串的内容; 例如上面的\g<0>匹配Hello Arroz, Nihao Arroz |
详见: http://blog.5ibc.net/p/80058.html |
4 ● 反向引用的案例
match(pattern, string, flags=0) returns the first match(返回_sre.SRE_Match对象) from the beginning of the string, if any; otherwise, a "NoneType" object. search(pattern, string, flags=0) returns the first match(返回_sre.SRE_Match对象) within the whole string, if any; otherwise, a "NoneType" object. ※ flags 标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。
findall() returns a list of all non-overlapping matches(in the tuple form), if any; otherwise, an empty list. finditer() return an iterator yielding match objects over all non-overlapping matches for the RE pattern in string, if any; otherwise, an empty generator.
match(string[, pos[, endpos]])方法在字符串开头或指定位置进行搜索,模式必须出现在字符串开头或指定位置; search(string[, pos[, endpos]])方法在整个字符串或指定范围中进行搜索; findall(string[, pos[, endpos]])方法在字符串指定范围中查找所有符合正则表达式的字符串并以列表形式返回。 |
m.group() == m.group(0) == 返回模式(pattern)匹配的所有字符,与括号无关 m.group(N) 返回第N组括号(第N个子模式(subpattern))匹配的字符 m.groups() |
import re pat = re.compile(r"(\d{4})-(\d{2})-(\d{2})") m1 = re.match(pat, "2017-09-10, 2017-09-11") print(m1.groups()) # ('2017', '09', '10') print(m1.group()) # '2017-09-10' print(m1.group(0)) #'2017-09-10' ''' m1.group(1) #'2017' m1.group(2) # '09' m1.group(1,2) #('2017', '09') m1.group(3) # '10' m1.group(4) Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: no such group '''
m2 = re.search(pat, "2017-09-10, 2017-09-11") m2.groups() # ('2017', '09', '10') m2.group() # '2017-09-10' ''' m2.group(0) # '2017-09-10' m2.group(1) # '2017' m2.group(2) # '09' m2.group(3) # '10' m2.group(4) Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: no such group '''
lst = re.findall(pat, "2017-09-10, 2017-09-11") print(lst) # [('2017', '09', '10'), ('2017', '09', '11')]
it = re.finditer(pat, "2017-09-10, 2017-09-11") print(it) # <callable_iterator object at 0x0000000002943A20> print('--------------')
for matchnum, match in enumerate(it): print(match.group()) print(match.groups()) for group_num in range(0, len(match.groups())): group_num +=1 print(match.group(group_num)) ''' 2017-09-10 ('2017', '09', '10') 2017 09 10 2017-09-11 ('2017', '09', '11') 2017 09 11 ''' |
5 ● 命名分组(named grouping)
反斜杠加g以及中括号内一个名字,即:\g<name>,对应着命了名的组,named group (?P<name>expr)是分组(grouping): 除了原有的编号外, 再给匹配到的字符串expr指定一个额外的别名 (?P=expr)是反向引用/回溯(back reference): 引用别名为<name>的分组匹配到的字符串
text = "Hello Arroz, Nihao Arroz" ret = re.sub(r"Hello (?P<name>\w+), Nihao (?P=name)", "\g<name>",text) print(ret) # Arroz 注意: (?P=name)是反向引用(reference), (?<name>) |
import re m = re.search(r"\d{4}-(?P<na>\d{2})-\d{2}", "2006-09-03") print(m.group('na')) # 09 |
import re m = re.search(r'(\d{4})-(?:\d{2})-(\d{2})', "2006-09-03") # Non-capturing group(非捕获组) m.groups() # ('2006', '03') m.group(1) # '2006' m.group(2) # '03' # (?:\d{2})这一组被忽略 m.group(3) ''' Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: no such group ''' |
※ MatchObject的另外几个方法:
groupdict(default=None):返回包含匹配的所有命名子模式内容的字典 start([group]):返回指定子模式内容的起始位置 end([group]):返回指定子模式内容的结束位置的前一个位置 span([group]):返回一个包含指定子模式内容起始位置和结束位置前一个位置的元组。 |
import re text = "Hello Arroz, Nihao Alex" pat=re.compile(r"Hello (?P<name1>\w+), Nihao (?P<name2>\w+)") mo= re.search(pat, text) print(mo.group('name1')) # Arroz print(mo.groupdict()) # {'name1': 'Arroz', 'name2': 'Alex'} print(mo.span()) # (0, 23) print(mo.span(0)) # (0, 23) print(mo.span(1)) # (6, 11) print(mo.start(1)) # 6 print(mo.end(1)) # 11 print(mo.span(2)) # (19, 23) |
# fullmatch(pattern, string, flags=0) 尝试把模式作用于整个字符串,返回match对象或None import re text = "Hello Arroz, Nihao Alex" pat=re.compile(r"Hello (?P<name1>\w+), Nihao (?P<name2>\w+)") is_full_match = re.fullmatch(pat, text) print("isfullmatch:", is_full_match) # isfullmatch: <_sre.SRE_Match object; span=(0, 23), match='Hello Arroz, Nihao Alex'> # 如果不完全匹配, 返回:isfullmatch: None |
# escape(string) 将字符串中所有的非字母, 非数字字符转义(escape all non-alphanumerics) print(re.escape('http://www.py thon.org')) # http\:\/\/www\.py\ thon\.org→Pycharm的结果 # 'http\\:\\/\\/www\\.py\\ thon\\.org'→cmd的结果 |
# expand(template) 将匹配到的分组代入template中然后返回。template中可以使用 \id 、\g<id> 、\g<name> 引用分组。id为捕获组的编号,name为命名捕获组的名字。 import re s="abcdefghijklmnopqrstuvwxyz" pattern=r'(\w)(\w)(\w)(\w)(\w)(\w)(\w)(\w)(\w)(\w)(\w)(\w)(\w)' m=re.search(pattern,s) print(m.expand(r'\1'), m.expand(r'\10'), m.expand(r'\g<10>')) # a j j
# purge() 清空正则表达式缓存 |
6 ● 文本编辑器(EmEditor, NotePad++)中匹配汉字字符
Python中匹配汉字字符, 用平时见到的统一字名的形式就可以了: [\u4e00-\u9fa5] 但是在文本编辑器(EmEditor, NotePad++)中, 需要把上面的形式改为(x表示十六进制): [\x{4e00}-\x{9fa5}] 或者: [一-龥] 就可以实现匹配中文了.
单独的统一字名加不加中括号都可以. |
详见:http://www.crifan.com/answer_question_notepadplusplus_regular_expression_match_chinese_character |
● 补充
\num 此处的num是一个正整数。例如,"(.)\1"匹配两个连续的相同字符, 如abccde \f 换页符匹配 |
十七. Python基础(17)--正则表达式的更多相关文章
- python基础(17):正则表达式
1. 正则表达式 1.1 正则表达式是什么 正则表达式本身也和python没有什么关系,就是匹配字符串内容的一种规则. 官方定义:正则表达式是对字符串操作的一种逻辑公式,就是用事先定义好的一些特定字符 ...
- Python基础之 正则表达式指南
本文介绍了Python对于正则表达式的支持,包括正则表达式基础以及Python正则表达式标准库的完整介绍及使用示例.本文的内容不包括如何编写高效的正则表达式.如何优化正则表达式,这些主题请查看其他教程 ...
- python基础之正则表达式
正则表达式语法 正则表达式 (或 RE) 指定一组字符串匹配它;在此模块中的功能让您检查一下,如果一个特定的字符串匹配给定的正则表达式 (或给定的正则表达式匹配特定的字符串,可归结为同一件事). 正则 ...
- Python高手之路【五】python基础之正则表达式
下图列出了Python支持的正则表达式元字符和语法: 字符点:匹配任意一个字符 import re st = 'python' result = re.findall('p.t',st) print( ...
- python基础之正则表达式和re模块
正则表达式 就其本质而言,正则表达式(或 re)是一种小型的.高度专业化的编程语言,(在Python中)它内嵌在Python中,并通过 re 模块实现.正则表达式模式被编译成一系列的字节码,然后由用 ...
- python基础之 正则表达式,re模块
1.正则表达式 正则表达式:是字符串的规则,只是检测字符串是否符合条件的规则而已 1.检测某一段字符串是否符合规则 2.将符合规则的匹配出来re模块:是用来操作正则表达式的 2.正则表达式组成 字符组 ...
- python基础-RE正则表达式
re 正则表示式 正则表达式(或 RE)是一种小型的.高度专业化的编程语言,(在Python中)它内嵌在Python中,并通过 re 模块实现.正则表达式模式被编译成一系列的字节码,然后由用 C 编写 ...
- python基础之正则表达式。
简介 就其本质而言,正则表达式是内嵌在python内,由re模块实现,小型的专业化语言,最后由c写的匹配引擎执行.正则表达式(regular expression)描述了一种字符串匹配的模式,可以用来 ...
- Python开发【第一篇】Python基础之正则表达式补充
正则表达式 一简介:就其本质而言,正则表达式(或RE)是一种小型的.高度专业化的标称语言,(在Python中)它内嵌在Python中,并通过re模块实现.正则表达式模式被编译成一系列的字节码,然后由用 ...
随机推荐
- centos php5.4 升级 php7
接上篇,edusoho需要php5.5以上版本,于是需要升级本地php php是通过yum默认安装的.以下安装参考 link https://blog.csdn.net/u012569217/arti ...
- QQ Protect 的删除
删的好费劲,驱动程序,服务,各个东西都在相互保护. 最后总结: 1)进安全模式 2)删除 下面的文件 c:\program files\tencent\qqlite\shellext\qqshelle ...
- MySql常用函数 --MySql
1.目标 MySQL数据库中提供了很丰富的函数.MySQL函数包括数学函数.字符串函数.日期和时间函数.条件判断函数.系统信息函数.加密函数.格式化函数等.通过这些函数,可以简化用户的操作.例如,字符 ...
- BGP - 1,基本概念
1,BGP知识点 a)AS号:私有(64512-65535),公有(0-64511). b)什么时候使用BGP:有数据穿越本AS前往其他AS:本AS有多条到其他AS的连接:必须要做策略. c)BG ...
- You Don't Know JS: Async & Performance(第一章, 异步:now & later)
Chapter 1: Asynchrony: Now & Later 在一门语言中,比如JavaScript, 最重要但仍然常常被误解的编程部分是如何在一个完整的时间周期表示和操作程序行为. ...
- hdu-4507 吉哥系列故事——恨7不成妻 数位DP 状态转移分析/极限取模
http://acm.hdu.edu.cn/showproblem.php?pid=4507 求[L,R]中不满足任意条件的数的平方和mod 1e9+7. 条件: 1.整数中某一位是7:2.整数的每一 ...
- 矩阵最优路线DP
母题:矩阵中每个点有权值,每经过一个点就累加权值,求从a点到b点的最优(最大)路线. 题型1: 从左上到右下,只能向下或者向右 for 行 for 列 dp=max dp左,dp上; 扫一遍就行 有时 ...
- Confluence 6 为一个空间应用一个主题
主题允许你对 Confluence 的外表和显示进行自定义.你的 Confluence 空间管理员可以到 The Atlassian Marketplace 上下载主题. 一旦一个主题被安装到 Con ...
- 【模板/经典题型】树上第k大
直接对树dfs一发,对每个节点建出主席树. 查询的时候主席树上二分,四个参数x+y-lca(x,y)-fa[lca(x,y)]. 如果要求支持动态加边的话,只需要一个启发式合并即可,每次暴力重构主席树 ...
- springcloud之eureka配置——eureka.instance
1.在springcloud中服务的 Instance ID 默认值是: ${spring.cloud.client.hostname}:${spring.application.name}:${sp ...