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.模块的简单认识定义:模块就是我们把装有特定功能 ...
随机推荐
- Java 静态内部类注意点
静态内部类(嵌套类)的对象除了没有对生成它的外部类对象的引用特权外,与其他所有内部类完全一样. 在内部类不需要访问外部类时,应该使用静态内部类(嵌套类). 与常规内部类不同的是,静态内部类可以拥有静态 ...
- [LeetCode] Falling Squares 下落的方块
On an infinite number line (x-axis), we drop given squares in the order they are given. The i-th squ ...
- Fetching data with Ajax小例子
ajax获取数据示例: 示例1 通过ajax获取txt文件里面的内容示例: <html> <head> <title>Ajax at work</title& ...
- bzoj 5285: [Hnoi2018]寻宝游戏
Description Solution 把输入的 \(n\) 个二进制数看作一个大小为 \(n*m\) 的矩阵 把每一列压成一个二进制数,其中最高位是最下面的元素 然后就有了 \(m\) 个二进制数 ...
- hdu 5521 最短路
Meeting Time Limit: 12000/6000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)Total ...
- USACO 2017 February Gold
那天打cf前无聊练手 T1.Why Did the Cow Cross the Road 题目大意:N*N的矩阵,从左上角走到右下角,走一步消耗T,每走3步消耗当前所在位置上的权值,求最小消耗 思路: ...
- codeforces round #419 A. Karen and Morning
Karen is getting ready for a new school day! It is currently hh:mm, given in a 24-hour format. As yo ...
- ●HDU 3507 Print Article
题链: http://acm.hdu.edu.cn/showproblem.php?pid=3507 题解: 斜率优化DP 一个入门题,就不给题解了,网上的好讲解很多的. 这里就只提一个小问题吧( ...
- C语言程序第三次作业
(一)改错题 计算f(x)的值:输入实数x,计算并输出下列分段函数f(x)的值,输出时保留1位小数. 输入输出样例1: Enterr x: 10.0 f(10.0) = 0.1 输入输出样例2: En ...
- es6新增
首先要说let,他是只在代码块中执行的变量,例如: { let a = 10; var b = 1;}console.log(a);//definedconsole.log(b);//1 ...