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.模块的简单认识定义:模块就是我们把装有特定功能 ...
随机推荐
- [LeetCode] Optimal Division 最优分隔
Given a list of positive integers, the adjacent integers will perform the float division. For exampl ...
- 【实验吧】CTF_Web_简单的SQL注入之2
直接输入11'报语法错误,然后输入1' and '1'='1 报SQLi detected!,说明有防护,输入1'and'1'='1回显ID: 1'and'1'='1 name: baloteli ...
- 数轴line
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAq8AAAGaCAYAAAAhPqoeAAAgAElEQVR4nOzdCbh2U/k/8C0NpkgRzZ
- UVA129 —— Krypton Factor (氪因素)
Input and Output In order to provide the Quiz Master with a potentially unlimited source of question ...
- [USACO 5.1.3]乐曲主题
Description 我们用N(1 <= N <=5000)个音符的序列来表示一首乐曲,每个音符都是1..88范围内的整数,每个数表示钢琴上的一个键.很不幸这种表示旋律的方法忽略了音符的 ...
- hdu 5475(线段树)
题意: 两个操作:① 当为1时 ,乘上后面的数 ② 当为2时,除以第x次乘的数 还说了2操作后面的n不会重复(就这明显看出线段树- -,然而并没有看出来,还是靠的队友) 1则对每个节点赋值,2则将相应 ...
- [bzoj1901]动态区间k大
定一个含有n个数的序列a[1],a[2],a[3]……a[n],程序必须回答这样的询问:对于给定的i,j,k,在a[i],a[i+1],a[i+2]……a[j]中第k小的数是多少(1≤k≤j-i+1) ...
- Server-U FTP与AD完美集成方案详解
最近咱有个任务,那就是把公司的文件服务器.FTP服务器.邮件服务器进行迁移并作相应的整合.登陆后台查看了,公司目前正在使用的方案.FTP服务器使用的是Server-u FTP,验证方式选择的windo ...
- audioplayer.js插件的使用及小bug
之前在项目里用audioplayer.js做的一个页面,改了布局样式,还有插件自身有个bug就是audio添加autoplay属性后有两个音频播放,其中一个无法控制,会一直播放,我查看了官网的demo ...
- SVN错误:SVN Working copy XXX is too old
出错原因: 这是因为使用了低版本的svn生成了.svn内文件内容,但是,使用高版本svn同步时便出现该问题. 解决方法: 找到报错对应的文件夹,里面有个名为.svn的文件夹,删除这个文件夹(这是svn ...