【Python内置包】re.sub功能
之前要用到正则替换,所以就用到了sub这个功能,看着doc里写的云里雾里的,就自己做了做实验
re.sub(pattern, repl, string, count=0, flags=0) 先说功能
Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl.
就是先去找到string之中可以匹配pattern的部分,然后将这些部分替换成repl 再看看参数情况 第一个参数pattern:就是正则式字符串或者正则式对象 第二个参数repl:就是要用什么东西去替换pattern匹配到的字符串 第三个参数string:就是对哪个字符串进行匹配与替换 第四个参数count:就是只替换前几个,如果是0则全部都替换 先来看python doc给的官方示例
pattern = rdefs+([a-zA-Z_][a-zA-Z_0-9]*)s*(s*):
rep = rstatic PyObject*
py_1(void)
{
s = def myfunc():
re.sub(pattern, rep, s)
#static PyObject*
py_myfunc(void)
{
可以看到的是,pattern 这个正则式,成功匹配了s这个字符串,本应把这个字符串全部替换为 static PyObject* py_1(void) {
但我们发现1的位置变成myfunc,这是为啥呢 因为在正则表达式的规范里,每一对小括号都代表了一个组,从左往右数第一个括号里的叫做第一组,第二个括号里的内容叫做第二组。也就是说pattern这个正则式中,第一组是 [a-zA-Z_][a-zA-Z_0-9]* 并且只有第一组 因此在repl参数里,1就代表着:pattern中第一组正则表达式匹配到的内容,也就是myfunc 并且1这种用法在pattern里面仍然可以用,我们看下一个例子
input="python,123,python" output = re.sub(r"(w+),(d+),1",r"rep",input) print(output="+output+") #output=rep
我们发现这个表达式匹配成功,并且把字符串替换掉了,也就是说1代表了(w+)的匹配内容,也就是python
input="python,123,python" output = re.sub(r"(w+),(d+),2",r"rep",input) print(output="+output+") #output="python,123,python"
我们发现这个表达式匹配失败,没有把字符串替换掉,因为2代表了(d+)的匹配内容,也就是123
input=python,123,123` output = re.sub(r"(w+),(d+),2",r"rep",input) print(output="+output+") #output="python,123,python"
我们发现这个表达式匹配成功,把字符串替换掉了
承接pythondoc的例子我们再做一次实验
input="python,123,123" output = re.sub(r"(w+),(d+),2",r"rep:1,2,2,1",input) print(output="+output+") #output="rep:python,123,123,python"
