正则表达式用于匹配中的写入
在使用正则表达式的时候,我们通常是用它来提取某些信息。如果我想做的是把匹配到的内容替换成其他的值……
现在我正在这样做……
def getExpandedText(pattern, text, replaceValue):
"""
One liner... really ugly but it's only used in here.
"""
return text.replace(text[text.find(re.findall(pattern, text)[0]):], replaceValue) + \
text[text.find(re.findall(pattern, text)[0]) + len(replaceValue):]
所以如果我做类似这样的事情
>>> getExpandedText("aaa(...)bbb", "hola aaaiiibbb como estas?", "ooo")
'hola aaaooobbb como estas?'
它会把 (...) 替换成 'ooo'。
你们知道在Python的正则表达式中我们能否做到这一点吗?
非常感谢大家!!
5 个回答
1
当然可以。你可以看看编译后的正则表达式中的'sub'和'subn'方法,或者're.sub'和're.subn'这两个函数。你可以让它用你提供的字符串来替换匹配的部分,或者你也可以传入一个可调用的对象(比如一个函数),这个对象会被调用来提供替换的内容。详细信息可以查看这个链接。
2
你想使用 re.sub 这个功能:
>>> import re
>>> re.sub(r'aaa...bbb', 'aaaooobbb', "hola aaaiiibbb como estas?")
'hola aaaooobbb como estas?'
如果你想在替换的内容中再次使用模式里的某些变量部分,可以在替换字符串中使用 \g<n>
来访问第 n 个 ()
组:
>>> re.sub( "(svcOrdNbr +)..", "\g<1>XX", "svcOrdNbr IASZ0080")
'svcOrdNbr XXSZ0080'
7
sub (replacement, string[, count = 0])
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'
sub 函数会返回一个新字符串,这个字符串是把原字符串中最左边的、不重叠的正则表达式匹配到的部分替换成你指定的内容。如果没有找到匹配的部分,原字符串就会保持不变。