(?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. hdu 3954 线段树 (标记)

    Level up Time Limit: 10000/3000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total ...

  2. 洛谷4月月赛R1 Happy Poppin' Party Train

    来自FallDream的博客,未经允许,请勿转载,谢谢. 听学长说的就来玩一玩,随便乱打打  没想到一堆人被取消了成绩,莫名混了个Rank3 还有第一题数据肯定是有问题 --------------- ...

  3. bzoj2127

    2127: happiness Time Limit: 51 Sec  Memory Limit: 259 MBSubmit: 2492  Solved: 1205[Submit][Status][D ...

  4. 勤拂拭软件系列教程 之 Android开发之旅

    勤拂拭软件工作室持续推出Android开发系列教程与案例,供广大朋友分享交流技术经验,帮助喜欢Android的朋友们学习进步: 1. 勤拂拭软件Android开发之旅(1) 之 Android 开发环 ...

  5. java开发笔记

    replace与replaceAll的区别 replace的参数是char和CharSequence,即可以支持字符的替换,也支持字符串的替换(CharSequence即字符串序列的意思,说白了也就是 ...

  6. Unique-paths (动态规划)

    题目描述 A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below) ...

  7. PSR-4 自动加载器

    div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,cod ...

  8. 如何查看cisco 生成树状态

    如何查看cisco 生成树状态  Role(角色): 1.Desg(指定端口)   2.Root(根端口)    3.Altn(替换端口) Sts(状态): 1.FWD(转发)      2.BLK( ...

  9. javascript装饰器模式

    装饰器模式 什么是装饰器 原名decorator 被翻译为装饰器 可以理解为装饰 修饰 包装等意 现实中的作用 一间房子通过装饰可以变得更华丽,功能更多 类似一部手机可以单独使用 但是很多人都愿意家个 ...

  10. 58. Length of Last Word(easy, 字符串问题)

    Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the l ...