Python re.sub 使用起来很方便,写 python 代码常常都会用到。了解它的用法是很有必要的。
源代码中定义如下:
def sub(pattern, repl, string, count=0, flags=0):
"""Return the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in string by the
replacement repl. repl can be either a string or a callable;
if a string, backslash escapes in it are processed. If it is
a callable, it's passed the match object and must return
a replacement string to be used."""
return _compile(pattern, flags).sub(repl, string, count)
pattern
可以是一个字符串也可以是一个正则表达式,用于匹配要替换的字符,如果不写,字符串不做修改。-
repl
是将会被替换的值,repl可以是字符串也可以是一个方法。如果是一个字符串,反斜杠会被处理为逃逸字符,如\n会被替换为换行,等等。repl如果是一个function,每一个被匹配到的字段串执行替换函数。
\g<1>
代表前面pattern里面第一个分组,可以简写为\1
,\g<0>
代表前面pattern匹配到的所有字符串。 - count是pattern被替换的最大次数,默认是0会替换所有。有时候可能只想替换一部分,可以用到count
示例 1:
import re
a = re.sub(r'hello', 'i love www.coolcou.com', 'hello world')
print(a)
执行结果:
示例 2:
import re
a = re.sub(r'(\d+)', '100', 'www.coolcou.com is 3 yeas old!')
print(a)
执行结果:
示例 3:
import re
a = re.sub(r'(\d+).*', '\g<1> good tutorial website!', 'www.coolcou.com is 3 yeas old!')
print(a)
示例 4:
import re
str1 = '<ol start="4" data-tool="mdnice编辑器" style="margin-top: 8px;margin-bottom: 8px;padding-left: 25px;color: black;" class="list-paddingleft-2">'
str2 = '<ol data-tool="mdnice编辑器" style="margin-top: 8px;margin-bottom: 8px;padding-left: 25px;color: black;" class="list-paddingleft-2">'
a = re.sub(r'<ol .*?(start=".*?"){0,1}.*?>', '<ol \g<1>>', str1)
print(a)
b = re.sub(r'<ol .*?(start=".*?"){0,1}.*?>', '<ol \g<1>>', str2)
print(b)
执行结果:
示例 5:
import re
def replace_num(str):
numDict = {'0':'〇','1':'一','2':'二','3':'三','4':'四','5':'五','6':'六','7':'七','8':'八','9':'九'}
print(str.group())
return numDict[str.group()]
my_str = '2018年6月7号'
a = re.sub(r'(\d)', replace_num, my_str)
print(a) #每次匹配一个数字,执行函数,获取替换后的值
执行结果:
评论前必须登录!
注册