Python 3 re模块3个括号相关的语法
(?aiLmsux)
(One or more letters from the set 'a', 'i', 'L', 'm', 's', 'u', 'x'.) The group matches the empty string; the letters set the corresponding flags: re.A (ASCII-only matching), re.I (ignore case), re.L (locale dependent), re.M (multi-line), re.S (dot matches all), and re.X (verbose), for the entire regular expression. (The flags are described in Module Contents.) This is useful if you wish to include the flags as part of the regular expression, instead of passing a flag argument to the re.compile() function.
Note that the (?x) flag changes how the expression is parsed. It should be used first in the expression string, or after one or more whitespace characters. If there are non-whitespace characters before the flag, the results are undefined.
>>> re.findall(r'(?a)[abcd]','aBcD')
['a', 'c']
>>> re.findall(r'(?i)[abcd]','aBcD')
['a', 'B', 'c', 'D']
>>> re.findall(r'[abcd](?i)','aBcD')
['a', 'B', 'c', 'D']
>>> re.findall(r'[abcd](?a)','aBcD')
['a', 'c']
>>> re.findall(r'[abcd](?a)(?i)','aBcD')
['a', 'B', 'c', 'D']
>>> re.findall(r'(?a)[abcd](?i)','aBcD')
['a', 'B', 'c', 'D']
(?P<name>...)
Similar to regular parentheses, but the substring matched by the group is accessible via the symbolic group name name. Group names must be valid Python identifiers, and each group name must be defined only once within a regular expression. A symbolic group is also a numbered group, just as if the group were not named.
Named groups can be referenced in three contexts. If the pattern is (?P<quote>['"]).*?(?P=quote) (i.e. matching a string quoted with either single or double quotes):
(?P<quote>['"]).*?(?P=quote)就相当于(['"]).*?\1
Context of reference to group “quote” | Ways to reference it |
---|---|
in the same pattern itself |
|
when processing match object m |
|
in a string passed to the repl argument of re.sub() |
|
这个语法感觉主要适用于正则表达式中括号结构比较繁杂的情况,如下,当你只想要(\w{2,4})提取到的字符串时,你得数左边有多少对括号,嗯,看来是4对,那么我用5就可以访问到它:
>>> m=re.search(r'((\w)(\d(\w)))(\w{2,4})\1','a1atesta1a')
>>> m.group(5)
'test'
如果把它改写成(?P<t>\w{2,4}),你就可以通过m.group('t')达到目的,而不用去数前面有多少对括号.
>>> m=re.search(r'((\w)(\d(\w)))(?P<t>\w{2,4})\1','a1atesta1a')
>>> m.group('t')
'test'
反过来说,如果括号结构比较简单,则没必要用它,直接\number就可以了.比如说:
>>> m=re.search(r'(\w)(\d)','a2b3c')
>>> m.group(1)
'a'
>>> m.group(2)
'2'
>>>
(?P=name)
A backreference to a named group; it matches whatever text was matched by the earlier group named name.
实战举例
比如你想提取test.py文件中所有字面量字符串里面的内容(即ab,ab,a\nb,a\nb):
正则表达式可以这样写:
r'(?s)(?P<quote>"""|\'\'\'|\'|")(?P<t>.*?)(?P=quote)'
>>> import re
>>> quote_pat=re.compile(r'(?s)(?P<quote>"""|\'\'\'|\'|")(?P<t>.*?)(?P=quote)')
>>> [x.group('t') for x in re.finditer(quote_pat,open('test.py').read())]
['ab', 'ab', 'a\nb', 'a\nb']
如果想对提取到的字符加个'x'前缀和'z'后缀,再写回test.py文件:
>>> s=re.sub(quote_pat,'\g<quote>x\g<t>z\g<quote>',open('test.py').read())
>>> open('test.py','w').write(s)
46
结果:
也可以这样写:
>>> quote_pat=re.compile(r'(?s)("""|\'\'\'|\'|")(.*?)\1')
>>> s=re.sub(quote_pat,r'\1x\2z\1',open('test.py').read())
>>> open('test.py','w').write(s)
54
在括号结构并不复杂的情况下,\number写法要简单清晰.不过要注意加r前缀,否则\1会被认为是ASCII字符,而不是正则表达式中的特殊字符.
最后补个re.sub函数使用经验.对于re.sub(pattern, repl, string, count=0, flags=0),参数pattern和repl的字符串表达式建议一律加r前缀.
因为对于repl参数来说,'\n','\\n'和r'\n'三者是等效的,而'\\1'和r'\1'等效,'\1'和r'\1'却不等效.这真是一种奇特的规则.为了防止意外惊喜,一律加r前缀.
Python 3 re模块3个括号相关的语法的更多相关文章
- Python之常用模块三(面向对象相关的三个模块)
hashlib.configparser.logging模块 一.常用模块二 hashlib模块 hashlib提供了常见的摘要算法,如md5和sha1等等. 那么什么是摘要算法呢?摘要算法又称为哈希 ...
- python(九)re模块
python中re模块提供了正则表达式相关操作. 1. 字符串匹配: . 匹配除换行符以外的任意字符 \w 匹配字符或数字或下划线或汉字 \s 匹配任意空白字符 \d 匹配数字 \b 匹配单词 ...
- python 浅析模块,包及其相关用法
今天买了一本关于模块的书,说实话,模块真的太多了,小编许多也不知道,要是把模块全讲完,可能得出本书了,所以小编在自己有限的能力范围内在这里浅析一下自己的见解,同时讲讲几个常用的模块. 这里是2018. ...
- python浅析模块,包及其相关用法
一,模块 什么是模块? 在计算机程序的开发过程中,随着程序代码越写越多,在一个文件里面,代码会越来越长,越来越不容易维护. 为了编写可以维护的代码,我们把很多函数分组,分别放到不同额文件,这样,每个文 ...
- 【9】python关于os模块与os.path的相关操作
---恢复内容开始--- #__author:"吉*佳" #date: 2018/10/20 0020 #function: # os模块知识点 import os # 获取平台名 ...
- 学习PYTHON之路, DAY 6 - PYTHON 基础 6 (模块)
一 安装,导入模块 安装: pip3 install 模块名称 导入: import module from module.xx.xx import xx from module.xx.xx impo ...
- python正则表达式——re模块
http://blog.csdn.net/zm2714/article/details/8016323 re模块 开始使用re Python通过re模块提供对正则表达式的支持.使用re的一般步骤是先将 ...
- 周末班:Python基础之模块
什么是模块 什么是模块? 常见的场景:一个模块就是一个包含了python定义和声明的文件,文件名就是模块名字加上.py的后缀. 但其实import加载的模块分为四个通用类别: 1 使用python编写 ...
- Python基础之模块以及5大模块的使用
内容梗概: 1. 模块的简单认识 2. collections模块 3. time时间模块 4. random模块 5. os模块 6. sys模块 1.模块的简单认识定义:模块就是我们把装有特定功能 ...
随机推荐
- div中的内容超过容器宽度的问题
问题描述: <div class="category"> <div class="column-a">排名</div> ...
- leetcode 717. 1-bit and 2-bit Characters -easy
https://leetcode.com/problems/1-bit-and-2-bit-characters/description/ We have two special characters ...
- IOS开发-UIDynamic(物理仿真)简单使用
UIDynamic是从IOS7开始引入的一种新技术,隶属于UIKit框架,我们可以认为是一种物理引擎能模拟和仿真现实生活中的物理现象,比如重力,弹性碰撞等. 可以让开发人员远离物理公式的情况下,实现一 ...
- 灰狼呼唤着同胞(brethren)
先求出确定边的联通块,有cnt块,显然方案数为2^(cnt-1) 联通块用dfs很好求 但此题还有并查集解法,且与一道叫团伙的题很像 边为0为敌人,1为朋友,敌人的敌人是朋友,朋友的朋友是朋友,正好对 ...
- hihocoder 1391 树状数组
#1391 : Countries 时间限制:1000ms 单点时限:1000ms 内存限制:256MB 描述 There are two antagonistic countries, countr ...
- ●ZOJ 2112 Dynamic Rankings
●赘述题目 对于一个长为n(n<50000)的序列(序列中的数小于1000000000),现有如下两种指令: Q a b c:询问区间[a,b]中第c小的数. C p b:将序列中的从左往右数第 ...
- bzoj4152[AMPPZ2014]The Captain 最短路
4152: [AMPPZ2014]The Captain Time Limit: 20 Sec Memory Limit: 256 MBSubmit: 1517 Solved: 603[Submi ...
- NTT+多项式求逆+多项式开方(BZOJ3625)
定义多项式$h(x)$的每一项系数$h_i$,为i在c[1]~c[n]中的出现次数. 定义多项式$f(x)$的每一项系数$f_i$,为权值为i的方案数. 通过简单的分析我们可以发现:$f(x)=\fr ...
- Python Socket第二篇(socketserver)
本节内容 socketserver基础知识 ThreadingTCPServer源码剖析 1.socketserver基础 ThreadingTCPServer实现的Soket服务器内部会为每个cli ...
- 修改SQL数据库中表字段类型时,报“一个或多个对象访问此列”错误的解决方法
在SQL数据库中使用SQL语句(格式:alter table [tablename] alter column [colname] [newDataType])修改某表的字段类型时,报一下错误:由于一 ...