-
API文档:
re.sub(pattern,repl,string[, count, flags])
-
Return the string obtained by replacing the leftmost non-overlapping occurrences ofpattern instring by the replacement repl. If the pattern isn’t found,string is returned unchanged.repl can be a string or a function; if it is a string, any backslash escapes in it are processed. That is,\n is converted to a single newline character,\r is converted to a linefeed, and so forth. Unknown escapes such as\j are left alone. Backreferences, such as\6, are replaced with the substring matched by group 6 in the pattern.
翻译文档:
参数:
pattern:匹配字符串的规则
repl:可以替换的字符串也可以是处理的函数
string:目标字符串
[count]:匹配替换的次数
[flags]:一些小标记,匹配时忽略字符串的大小写
描述:
返回string的字符串副本,根据匹配模式进行字符串替换和处理操作。
例子:
#! /usr/bin/env python
#coding=utf-8
import re
#匹配后处理函数
def dashrepl(matchObj):
if matchObj.group(0)=='-':
return ' '
else:
return '-'
print u'API文档例子:'+re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',
r'static PyObject*\npy_\1(void)\n{',
'def myfunc():')
#匹配字符串,替换字符串
print u'repl替换字符串:'+re.sub('-{1,1}','+','pro----gram-files')
#匹配字符串,调用dashrepl处理替换字符串
print u'repl为函数处理替换的字符串:'+re.sub('-{1,2}',dashrepl,'pro----gram-files')
#匹配替换匹配的次数
print u'替换匹配的次数:'+re.sub('-{1,1}','+','pro----gram-files',2)
#忽略匹配字符串的大小写
print u'flags 忽略字符串大小写:'+re.sub(r'\sAND\s',' & ','Baked Beans And Spam',flags=re.IGNORECASE)
输出:
API文档例子:static PyObject*
py_myfunc(void)
{
repl替换字符串:pro++++gram+files
repl为函数处理替换的字符串:pro--gram files
替换匹配的次数:pro++--gram-files
flags 忽略字符串大小写:Baked Beans & Spam