|
| 1 | +#!/usr/bin/env python |
| 2 | +# -*- encoding: utf-8 -*- |
| 3 | +""" |
| 4 | +Topic: 正则式分组替换示例 |
| 5 | +""" |
| 6 | +import re |
| 7 | + |
| 8 | + |
| 9 | +class Nth(object): |
| 10 | + """ |
| 11 | + 如果 sub 函数的第二个参数是个函数,则每次匹配到的时候都会执行这个函数。 |
| 12 | + 函数接受匹配到的那个 match object 作为参数,返回用来替换的字符串。 |
| 13 | + 利用这个特性就可以只在第 N 次匹配的时候返回要替换成的字符串,其他时候原样返回不做替换即可。 |
| 14 | + """ |
| 15 | + def __init__(self, nth, replacement): |
| 16 | + self.nth = nth |
| 17 | + self.replacement = replacement |
| 18 | + self.calls = 0 |
| 19 | + |
| 20 | + def __call__(self, matchobj): |
| 21 | + self.calls += 1 |
| 22 | + if self.calls == self.nth: |
| 23 | + return self.replacement |
| 24 | + return matchobj.group(0) |
| 25 | + |
| 26 | + |
| 27 | +def re_sub(): |
| 28 | + a = re.sub(r'(foo)(bar)', r'\g<1>123\g<2>', 'foobar') |
| 29 | + print(a) |
| 30 | + |
| 31 | + a = re.sub('a', 'A', 'abcasd') # 找到a用A替换,后面见和group的配合使用 |
| 32 | + pat = re.compile('a') |
| 33 | + b = pat.sub('A', 'abcasd') |
| 34 | + print(b) |
| 35 | + |
| 36 | + # 通过组进行更新替换: |
| 37 | + pat = re.compile(r'(www\.)(.*)(\..{3})') # 正则表达式 |
| 38 | + print(pat.match('www.dxy.com').group(2)) |
| 39 | + # 通过正则匹配找到符合规则的”www.dxy.com“ ,取得组2字符串,用baidu替换之 |
| 40 | + print('-----------') |
| 41 | + print(pat.sub(r'\g<1>baidu\g<3>', 'hello,www.dxy.com')) |
| 42 | + |
| 43 | + pat = re.compile(r'(\w+) (\w+)') |
| 44 | + s = 'hello world ! hello hz !' |
| 45 | + pat.findall('hello world ! hello hz !') |
| 46 | + # [('hello', 'world'), ('hello', 'hz')] |
| 47 | + # 通过正则得到组1(hello),组2(world),再通过sub去替换。即组1替换组2,组2替换组1,调换位置。 |
| 48 | + print(pat.sub(r'\2 \1', s)) |
| 49 | + |
| 50 | + # 替换字符串中第3个出现的good |
| 51 | + pat = re.compile(r'(good)') |
| 52 | + a = pat.sub(Nth(3, 'bad'), 'This is a good story, good is good. Oh, good') |
| 53 | + print(a) |
| 54 | + # 传入一个lambda函数,在匹配处两边加双引号 |
| 55 | + a = pat.sub(lambda mo: '"' + mo.group(0) + '"', 'This is a good story, good is ') |
| 56 | + print(a) |
| 57 | + |
| 58 | + |
| 59 | +if __name__ == '__main__': |
| 60 | + re_sub() |
| 61 | + |
0 commit comments