搜索和替换

其余常见的用途就是找到全部模式匹配的字符串并用不一样的字符串来替换它们。sub() 方法提供一个替换值,能够是字符串或一个函数,和一个要被处理的字符串。python

sub(replacement, string[, count = 0])

返回的字符串是在字符串中用 RE 最左边不重复的匹配来替换。若是模式没有发现,字符将被没有改变地返回。正则表达式

可选参数 count 是模式匹配后替换的最大次数;count 必须是非负整数。缺省值是 0 表示替换全部的匹配。函数

这里有个使用 sub() 方法的简单例子。它用单词 "colour" 替换颜色名。翻译

#!python
>>> p = re.compile( '(blue|white|red)')
>>> p.sub( 'colour', 'blue socks and red shoes')
'colour socks and colour shoes'
>>> p.sub( 'colour', 'blue socks and red shoes', count=1)
'colour socks and red shoes'

subn() 方法做用同样,但返回的是包含新字符串和替换执行次数的两元组。code

#!python
>>> p = re.compile( '(blue|white|red)')
>>> p.subn( 'colour', 'blue socks and red shoes')
('colour socks and colour shoes', 2)
>>> p.subn( 'colour', 'no colours at all')
('no colours at all', 0)

空匹配只有在它们没有紧挨着前一个匹配时才会被替换掉。对象

#!python
>>> p = re.compile('x*')
>>> p.sub('-', 'abxd')
'-a-b-d-'

若是替换的是一个字符串,任何在其中的反斜杠都会被处理。"\n" 将会被转换成一个换行符,"\r"转换成回车等等。未知的转义如 "\j" 则保持原样。逆向引用,如 "\6",被 RE 中相应的组匹配而被子串替换。这使你能够在替换后的字符串中插入原始文本的一部分。ci

这个例子匹配被 "{" 和 "}" 括起来的单词 "section",并将 "section" 替换成 "subsection"。字符串

#!python
>>> p = re.compile('section{ ( [^}]* ) }', re.VERBOSE)
>>> p.sub(r'subsection{\1}','section{First} section{second}')
'subsection{First} subsection{second}'

还能够指定用 (?P<name>...) 语法定义的命名组。"\g<name>" 将经过组名 "name" 用子串来匹配,而且 "\g<number>" 使用相应的组号。因此 "\g<2>" 等于 "\2",但能在替换字符串里含义不清,如 "\g<2>0"。("\20" 被解释成对组 20 的引用,而不是对后面跟着一个字母 "0" 的组 2 的引用。)string

#!python
>>> p = re.compile('section{ (?P<name> [^}]* ) }', re.VERBOSE)
>>> p.sub(r'subsection{\1}','section{First}')
'subsection{First}'
>>> p.sub(r'subsection{\g<1>}','section{First}')
'subsection{First}'
>>> p.sub(r'subsection{\g<name>}','section{First}')
'subsection{First}'

替换也能够是一个甚至给你更多控制的函数。若是替换是个函数,该函数将会被模式中每个不重复的匹配所调用。在每次调用时,函数会被传入一个 MatchObject 的对象做为参数,所以能够用这个对象去计算出替换字符串并返回它。it

在下面的例子里,替换函数将十进制翻译成十六进制:

#!python
>>> def hexrepl( match ):
...     "Return the hex string for a decimal number"
...     value = int( match.group() )
...     return hex(value)
...
>>> p = re.compile(r'\d+')
>>> p.sub(hexrepl, 'Call 65490 for printing, 49152 for user code.')
'Call 0xffd2 for printing, 0xc000 for user code.'

当使用模块级的 re.sub() 函数时,模式做为第一个参数。模式也许是一个字符串或一个RegexObject;若是你须要指定正则表达式标志,你必需要么使用 RegexObject 作第一个参数,或用使用模式内嵌修正器,如 sub("(?i)b+", "x", "bbbb BBBB") returns 'x x'。

相关文章
相关标签/搜索