正则表达式,但用于比赛
时间:2020-03-06 14:47:28 来源:igfitidea点击:
当使用正则表达式时,通常,如果不总是使用它们来提取某种信息。我需要的是将匹配值替换为其他值...
现在我正在做...
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正则表达式来做到这一点?
非常感谢大家!!
解决方案
当然。请参见已编译正则表达式的" sub"和" subn"方法,或者" re.sub"和" re.subn"函数。我们可以使它用我们提供的字符串参数替换匹配项,也可以传递将被调用以提供替换值的可调用函数(例如函数)。参见https://docs.python.org/library/re.html
sub (replacement, string[, count = 0])
sub返回通过用替换替换替换RE中字符串中最左边的RE不重叠而获得的字符串。如果找不到该模式,则字符串将原样返回。
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'
我们要使用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'
如果要继续使用提到的语法(替换匹配值而不是替换不匹配的部分),并且考虑到只有一组,可以使用下面的代码。
def getExpandedText(pattern, text, replaceValue):
m = re.search(pattern, text)
expandedText = text[:m.start(1)] + replaceValue + text[m.end(1):]
return expandedText
def getExpandedText(pattern,text,*group):
r""" Searches for pattern in the text and replaces
all captures with the values in group.
Tag renaming:
>>> html = '<div> abc <span id="x"> def </span> ghi </div>'
>>> getExpandedText(r'</?(span\b)[^>]*>', html, 'div')
'<div> abc <div id="x"> def </div> ghi </div>'
Nested groups, capture-references:
>>> getExpandedText(r'A(.*?Z(.*?))B', "abAcdZefBgh", r'<>')
'abA<ef>Bgh'
"""
pattern = re.compile(pattern)
ret = []
last = 0
for m in pattern.finditer(text):
for i in xrange(0,len(m.groups())):
start,end = m.span(i+1)
# nested or skipped group
if start < last or group[i] is None:
continue
# text between the previous and current match
if last < start:
ret.append(text[last:start])
last = end
ret.append(m.expand(group[i]))
ret.append(text[last:])
return ''.join(ret)
编辑:在替换字符串中允许捕获引用。

