(?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
  • (?P=quote) (as shown)
  • \1
when processing match object m
  • m.group('quote')
  • m.end('quote') (etc.)
in a string passed to the repl argument of re.sub()
  • \g<quote>
  • \g<1>
  • \1

这个语法感觉主要适用于正则表达式中括号结构比较繁杂的情况,如下,当你只想要(\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个括号相关的语法的更多相关文章

  1. Python之常用模块三(面向对象相关的三个模块)

    hashlib.configparser.logging模块 一.常用模块二 hashlib模块 hashlib提供了常见的摘要算法,如md5和sha1等等. 那么什么是摘要算法呢?摘要算法又称为哈希 ...

  2. python(九)re模块

    python中re模块提供了正则表达式相关操作. 1. 字符串匹配: .    匹配除换行符以外的任意字符 \w 匹配字符或数字或下划线或汉字 \s  匹配任意空白字符 \d 匹配数字 \b 匹配单词 ...

  3. python 浅析模块,包及其相关用法

    今天买了一本关于模块的书,说实话,模块真的太多了,小编许多也不知道,要是把模块全讲完,可能得出本书了,所以小编在自己有限的能力范围内在这里浅析一下自己的见解,同时讲讲几个常用的模块. 这里是2018. ...

  4. python浅析模块,包及其相关用法

    一,模块 什么是模块? 在计算机程序的开发过程中,随着程序代码越写越多,在一个文件里面,代码会越来越长,越来越不容易维护. 为了编写可以维护的代码,我们把很多函数分组,分别放到不同额文件,这样,每个文 ...

  5. 【9】python关于os模块与os.path的相关操作

    ---恢复内容开始--- #__author:"吉*佳" #date: 2018/10/20 0020 #function: # os模块知识点 import os # 获取平台名 ...

  6. 学习PYTHON之路, DAY 6 - PYTHON 基础 6 (模块)

    一 安装,导入模块 安装: pip3 install 模块名称 导入: import module from module.xx.xx import xx from module.xx.xx impo ...

  7. python正则表达式——re模块

    http://blog.csdn.net/zm2714/article/details/8016323 re模块 开始使用re Python通过re模块提供对正则表达式的支持.使用re的一般步骤是先将 ...

  8. 周末班:Python基础之模块

    什么是模块 什么是模块? 常见的场景:一个模块就是一个包含了python定义和声明的文件,文件名就是模块名字加上.py的后缀. 但其实import加载的模块分为四个通用类别: 1 使用python编写 ...

  9. Python基础之模块以及5大模块的使用

    内容梗概: 1. 模块的简单认识 2. collections模块 3. time时间模块 4. random模块 5. os模块 6. sys模块 1.模块的简单认识定义:模块就是我们把装有特定功能 ...

随机推荐

  1. 从零开始系列之vue全家桶(6)实战前的设计

    搭建好基本框架后我们应该先想一想个人博客应该有哪些功能呢? 为了更好的适应企业的要求,这里我将搭建一个非典型的博客. 在全部采用单页开发的情况下,使用vue-router,路由分别设置home.abo ...

  2. X5 Blink下文字自动变大

    在X5 Blink中,页面排版时会主动对字体进行放大,会检测页面中的主字体,当某一块的字体在我们的判定规则中,认为字体的字号较小,并且是页面中的主要字体,就会采用主动放大的操作.这显然不是我们想要的. ...

  3. OpenGL平面阴影

    几种绘制阴影的方法 在OpenGL中,比较常见的绘制阴影的方法有:shadow mapping,shadow volumes以及一种在红宝书上提及的适合在确定平面上绘制阴影的方法. 平面阴影 在确定的 ...

  4. 智能合约开发solidity编程语言开发一个以太坊应用区块链投票实例

    智能合约开发用solidity编程语言部署在以太坊这个区块链平台,本文提供一个官方实战示例快速入门,用例子深入浅出智能合约开发,体会以太坊构建去中心化可信交易技术魅力.智能合约其实是"执行合 ...

  5. [ZJOI 2007]Hide 捉迷藏

    Description 捉迷藏 Jiajia和Wind是一对恩爱的夫妻,并且他们有很多孩子.某天,Jiajia.Wind和孩子们决定在家里玩捉迷藏游戏.他们的家很大且构造很奇特,由N个屋子和N-1条双 ...

  6. [HNOI 2013]比赛

    Description 沫沫非常喜欢看足球赛,但因为沉迷于射箭游戏,错过了最近的一次足球联赛.此次联 赛共N支球队参加,比赛规则如下: (1) 每两支球队之间踢一场比赛. (2) 若平局,两支球队各得 ...

  7. python3 字符串str 教程

    字符串可以用单引号或双引号来创建. Python 不支持单字符类型,单字符也在Python也是作为一个字符串使用. 例: var1 = 'Hello World!' var2 = "Pyth ...

  8. 修改表单元素中placeholder属性样式、清除IE浏览器中input元素的清除图标和眼睛图标

    一.修改input元素placeholder属性样式 在做项目的时候,一般表单元素的placeholder属性样式都是使用浏览器默认的,但有时候为了追求设计上的美感需要修表单元素的placeholde ...

  9. Linux学习之CentOS(十八)-----恢复Ext3下被删除的文件与 使用grep恢复被删文件内容(转)

    前言 下面是这个教程将教你如何在Ext3的文件系统中恢复被rm掉的文件. 删除文件 假设我们有一个文件名叫 'test.txt' $ls -il test.txt 15 -rw-rw-r– 2 roo ...

  10. 【vuejs深入二】vue源码解析之一,基础源码结构和htmlParse解析器

    写在前面 一个好的架构需要经过血与火的历练,一个好的工程师需要经过无数项目的摧残. vuejs是一个优秀的前端mvvm框架,它的易用性和渐进式的理念可以使每一个前端开发人员感到舒服,感到easy.它内 ...