用于字符串替换的python正则表达式

问题描述:

我想替换包含以下单词的字符串部分“$%word $%” 我想用字典的值替换它,其中相应的键等于单词。用于字符串替换的python正则表达式

换句话说,如果我有一个字符串: “blahblahblah $%一句话$%blablablabla $%汽车$%” 和字典{一句话: '日wassup',汽车: '丰田'}

字符串将是“blahblahblah wassup blablablabla丰田”

你怎么能在Python中实现它,我想使用字符串替换和正则表达式。

使用re.sub与函数作为REPL参数:

import re 

text = "blahblahblah $%word$% blablablabla $%car$%" 
words = dict(word="wassup", car="toyota") 

def replacement(match): 
    try: 
     return words[match.group(1)] # Lookup replacement string 
    except KeyError: 
     return match.group(0) # Return pattern unchanged 

pattern = re.compile(r'\$%(\w+)\$%') 
result = pattern.sub(replacement, text) 

如果你想通过替换表在使用re.sub的时候,使用functools.partial

import functools 

def replacement(table, match): 
    try: 
     return table[match.group(1)] 
    except: 
     return match.group(0) 

table = dict(...) 
result = pattern.sub(functools.partial(replacement, table), text) 

...或实施__call__的课程:

class Replacement(object): 
    def __init__(self, table): 
     self.table = table 
    def __call__(self, match): 
     try: 
      return self.table[match.group(1)] 
     except: 
      return match.group(0) 

result = pattern.sub(Replacement(table), text) 
+0

如果字典是另一种方法创建什么?我将如何实施更换?我无法将参数添加到替换中。 – mabounassif

+0

与此问题非常相似; http://stackoverflow.com/questions/7182546/how-to-replace-the-nth-appearance-of-a-needle-in-a-haystack-python –

+0

@mabounassif - Let'replacement' take the dictionary作为参数,然后使用'functools.partial()'创建一个传递字典的单参数包装函数。我会更新我的答案来举一个例子。 –

re模块是你想要的。

虽然您可能想重新考虑您选择的分隔符。 $%可能会有问题,因为$是正则表达式中的保留字符。尽管如此,只要记住在模式中使用'\\$'r'\$'(这是一个原始字符串,非常有用,如果你在python中执行正则表达式的东西)。

import re 

text = "blahblahblah $%word$% blablablabla $%car$%" 
words = dict(word="wassup", car="toyota") 

regx = re.compile('(\$%%(%s)\$%%)' % '|'.join(words.iterkeys())) 

print regx.sub(lambda mat: words[mat.group(2)], text) 

结果

blahblahblah wassup blablablabla toyota