孤单中,你能够取得所有,除了品格。—— 司汤达《红与黑》

概述

后面一篇文章 python应用正则表达式从json字符串中取出特定字段的值 简略应用了 re 模块的办法,然而对其余的办法并不相熟,为了更全面的理解和应用 python 中的 re,这里将本人学习的过程记录下来。

应用爬虫爬取网页数据的过程中,须要利用各种工具解析网页中的数据,比方:etreeBeautifulSoupscrapy 等工具,然而性能最弱小的还是正则表达式,上面将对 python 的 re 模块办法做一个总结。

Python 通过 re 模块提供对正则表达式的反对。应用 re 的个别步骤是:

  1. 应用 re.compile(正则表达式) 将正则表达式的字符串模式编译为Pattern实例
  2. 应用Pattern实例提供的办法解决文本并取得匹配后果(一个Match实例)
  3. 应用Match实例取得信息,进行其余的操作

一个简略的例子:

# -*- coding: utf-8 -*-import reif __name__ == '__main__':    # 将正则表达式编译成Pattern对象    pattern = re.compile(r'hello')    # 应用Pattern匹配文本,取得匹配后果,无奈匹配时将返回None    match = pattern.match('hello world!')    if match:        # 应用Match取得分组信息        print(match.group()) # 输入后果:hello        

应用原生字符串定义正则表达式能够不便的解决转义字符的问题

原生字符串的定义形式为:r''

有了原生字符串,不须要手动增加本义符号,它会主动本义,写进去的表达式也更直观。

1. 应用 re

re.compile(strPattern[, flag]):

这个办法是Pattern类的工厂办法,用于将字符串模式的正则表达式编译为Pattern对象。

第一个参数:正则表达式字符串

第二个参数(可选):是匹配模式,取值能够应用按位或运算符'|'示意同时失效,比方 re.I | re.M

可选值如下:

  • re.I(re.IGNORECASE): 疏忽大小写(括号内是残缺写法,下同)
  • M(MULTILINE): 多行模式,扭转'^'和'$'的行为
  • S(DOTALL): 点任意匹配模式,扭转'.'的行为
  • L(LOCALE): 使预约字符类 \w \W \b \B \s \S 取决于以后区域设定
  • U(UNICODE): 使预约字符类 \w \W \b \B \s \S \d \D 取决于unicode定义的字符属性
  • X(VERBOSE): 具体模式。这个模式下正则表达式能够是多行,疏忽空白字符,并能够退出正文。以下两个正则表达式是等价的:

    a = re.compile(r"""\d +  # the integral part                   \.    # the decimal point                   \d *  # some fractional digits""", re.X)b = re.compile(r"\d+\.\d*")

re 提供了泛滥模块办法用于实现正则表达式的性能。这些办法能够应用Pattern实例的相应办法代替,惟一的益处是少写一行re.compile()代码,但同时也无奈复用编译后的Pattern对象。这些办法将在Pattern类的实例办法局部一起介绍。如下面这个例子能够简写为:

m = re.match(r'hello', 'hello world!')print m.group()

2. 应用 Pattern

Pattern 对象是一个编译好的正则表达式,通过 Pattern 提供的一系列办法能够对文本进行匹配查找。

Pattern 对象不能间接实例化,必须应用 re.compile() 来获取。

2.1 Pattern 对象的属性

Pattern 提供了几个可读属性用于获取表达式的相干信息:

  1. pattern: 编译时用的表达式字符串。
  2. flags: 编译时用的匹配模式,数字模式。
  3. groups: 表达式中分组的数量。
  4. groupindex: 以表达式中有别名的组的别名为键、以该组对应的编号为值的字典,没有别名的组不蕴含在内。
# -*- coding: utf-8 -*-import reif __name__ == '__main__':    text = 'hello world'    p = re.compile(r'(\w+) (\w+)(?P<sign>.*)', re.DOTALL)    print("p.pattern:", p.pattern)    print("p.flags:", p.flags)    print("p.groups:", p.groups)    print("p.groupindex:", p.groupindex)

输入后果如下:

p.pattern: (\w+) (\w+)(?P<sign>.*)p.flags: 48p.groups: 3p.groupindex: {'sign': 3}

2.2 Pattern 对象的办法

1. match(string[, pos[, endpos]]) | re.match(pattern, string[, flags]):

如果 string开始地位 可能找到这个正则款式的任意个匹配,就返回一个相应的 Match对象。

如果匹配过程中pattern无奈匹配,或者匹配未完结就已达到endpos,则返回None

posendpos 的默认值别离为 0len(string)

re.match() 无奈指定这两个参数,参数flags用于编译pattern时指定匹配模式。

留神:这个办法并不是齐全匹配。当pattern完结时若string还有残余字符,依然视为胜利。想要齐全匹配,能够在表达式开端加上边界匹配符'$'。

2. search(string[, pos[, endpos]]) | re.search(pattern, string[, flags]):

这个办法用于查找字符串中能够匹配胜利的子串。

stringpos下标处起尝试匹配pattern,如果pattern完结时仍可匹配,则返回一个Match对象;

若无奈匹配,则将pos1后从新尝试匹配;直到pos=endpos时仍无奈匹配则返回None。

posendpos的默认值别离为 0len(string)

re.search()无奈指定这两个参数,参数flags用于编译pattern时指定匹配模式。

一个简略的例子:

# -*- coding: utf-8 -*-import reif __name__ == '__main__':    # 将正则表达式编译成Pattern对象    pattern = re.compile(r'world')    # 应用search()查找匹配的子串,不存在能匹配的子串时将返回None    # 这个例子中应用match()无奈胜利匹配    match = pattern.search('hello world!')    if match:        # 应用Match取得分组信息        print(match.group()) # 输入后果:world
留神 match 办法 和 search 办法的区别

3. split(string[, maxsplit]) | re.split(pattern, string[, maxsplit]):

依照可能匹配的子串将string宰割后返回列表。

maxsplit 用于指定最大宰割次数,不指定将全副宰割。

# -*- coding: utf-8 -*-import reif __name__ == '__main__':    p = re.compile(r'\d+')    # 依照数字分隔字符串    print(p.split('one1two2three3four4')) # 输入后果:['one', 'two', 'three', 'four', '']

4. findall(string[, pos[, endpos]]) | re.findall(pattern, string[, flags]):

搜寻 string,以列表模式返回全副能匹配的子串。

#!/usr/bin/env python# -*- coding:utf-8 -*-import reif __name__ == '__main__':    p = re.compile(r'\d+')    # 找到所有的数字,以列表的模式返回    print(p.findall('one1two2three3four4')) # 输入后果:['1', '2', '3', '4']

5. finditer(string[, pos[, endpos]]) | re.finditer(pattern, string[, flags]):

搜寻 string,返回一个程序拜访每一个匹配后果(Match对象)的迭代器。

#!/usr/bin/env python# -*- coding:utf-8 -*-import reif __name__ == '__main__':    p = re.compile(r'\d+')    # 返回一个程序拜访每一个匹配后果(`Match`对象)的迭代器    for m in p.finditer('one1two2three3four4'):        print(m.group())  # 输入后果:1 2 3 4

6. sub(repl, string[, count]) | re.sub(pattern, repl, string[, count]):

应用 repl 替换 string 中每一个匹配的子串后返回替换后的字符串。
repl 是一个字符串时,能够应用 \id\g<id>\g<name>援用分组,但不能应用编号0。
repl 是一个办法时,这个办法该当只承受一个参数(Match对象),并返回一个字符串用于替换(返回的字符串中不能再援用分组)。
count用于指定最多替换次数,不指定时全副替换。

#!/usr/bin/env python# -*- coding:utf-8 -*-import reif __name__ == '__main__':    p = re.compile(r'(\w+) (\w+)')    s = 'i say, hello world!'    print(p.sub(r'\1 \2 hi', s))  # 输入后果:i say hi, hello world hi!    def func(m):        return m.group(1).title() + ' ' + m.group(2).title()    print(p.sub(func, s))  # 输入后果:I Say, Hello World!

7. subn(repl, string[, count]) |re.sub(pattern, repl, string[, count]):

subn() 办法与 sub() 办法的区别是返回后果不同:

subn() 办法返回的后果是一个元组:(替换后的字符串,替换次数)

sub() 办法返回的后果是一个字符串:替换后的字符串

#!/usr/bin/env python# -*- coding:utf-8 -*-import reif __name__ == '__main__':    p = re.compile(r'(\w+) (\w+)')    s = 'i say, hello world!'    print(p.subn(r'\1 \2 hi', s))  # 输入后果:('i say hi, hello world hi!', 2)    def func(m):        return m.group(1).title() + ' ' + m.group(2).title()    print(p.subn(func, s))  # 输入后果:('I Say, Hello World!', 2)

3. 应用 Match

Match对象是一次匹配的后果,蕴含了很多对于此次匹配的信息,能够应用Match提供的可读属性或办法来获取这些信息。

3.1 Match 对象的属性

  1. string: 匹配时应用的文本。
  2. re: 匹配时应用的Pattern对象。
  3. pos: 文本中正则表达式开始搜寻的索引。值与Pattern.match()Pattern.seach()办法的同名参数雷同。
  4. endpos: 文本中正则表达式完结搜寻的索引。值与Pattern.match()Pattern.seach()办法的同名参数雷同。
  5. lastindex: 最初一个被捕捉的分组的索引。如果没有被捕捉的分组,将为None。
  6. lastgroup: 最初一个被捕捉的分组的别名。如果这个分组没有别名或者没有被捕捉的分组,将为None。
# -*- coding: utf-8 -*-import reif __name__ == '__main__':    text = 'hello world'    p = re.compile(r'(\w+) (\w+)(?P<sign>.*)', re.DOTALL)    match = p.match(text)    if match:        print("match.re:", match.re)        print("match.string:", match.string)        print("match.endpos:", match.endpos)        print("match.pos:", match.pos)        print("match.lastgroup:", match.lastgroup)        print("match.lastindex:", match.lastindex)                # 输入后果如下:# match.re: re.compile('(\\w+) (\\w+)(?P<sign>.*)', re.DOTALL)# match.string: hello world# match.endpos: 11# match.pos: 0# match.lastgroup: sign# match.lastindex: 3

3.2 Match 对象的办法

1. group([group1, …]):

取得一个或多个分组截获的字符串,指定多个参数时将以元组模式返回。

group()能够应用编号也能够应用别名;

编号0代表整个匹配的子串;

不填写参数时,返回group(0);

没有截获字符串的组返回None;

2. groups([default]):

以元组模式返回全副分组截获的字符串,相当于调用group(1,2,…last);

default示意没有截获字符串的组以这个值代替,默认为None;

3. groupdict([default]):

返回已有别名的组的别名为键、以该组截获的子串为值的字典,没有别名的组不蕴含在内。default含意同上。

4. start([group]):

返回指定的组截获的子串在string中的起始索引(子串第一个字符的索引)。group默认值为0。

5. end([group]):

返回指定的组截获的子串在string中的完结索引(子串最初一个字符的索引+1)。group默认值为0。

6. span([group]):

返回(start(group), end(group))。

7. expand(template):

将匹配到的分组代入template中而后返回。template中能够应用\id\g<id>\g<name>援用分组,但不能应用编号0。\id\g<id>是等价的;但\10将被认为是第10个分组,如果你想表白\1之后是字符'0',只能应用\g<1>0

# -*- coding: utf-8 -*-import reif __name__ == '__main__':    import re    m = re.match(r'(\w+) (\w+)(?P<sign>.*)', 'hello world!')    print("m.group(1,2):", m.group(0, 1, 2, 3))    print("m.groups():", m.groups())    print("m.groupdict():", m.groupdict())    print("m.start(2):", m.start(2))    print("m.end(2):", m.end(2))    print("m.span(2):", m.span(2))    print(r"m.expand(r'\2 \1\3'):", m.expand(r'\2 \1\3'))# 输入后果:# m.group(1,2): ('hello world!', 'hello', 'world', '!')# m.groups(): ('hello', 'world', '!')# m.groupdict(): {'sign': '!'}# m.start(2): 6# m.end(2): 11# m.span(2): (6, 11)# m.expand(r'\2 \1\3'): world hello!

参考文章

python 官网文档

https://www.cnblogs.com/huxi/...