Python正则表达式字符串替换

1 投票
3 回答
1127 浏览
提问于 2025-04-17 00:18

我想把一个字符串里面的某些部分替换掉,这些部分包含像"$%word$%"这样的词。

简单来说,如果我有一个字符串:"blahblahblah $%word$% blablablabla $%car$%",还有一个字典{word:'wassup', car:'toyota'}。

那么替换后的字符串应该是:"blahblahblah wassup blablablabla toyota"。

我想知道怎么在Python里实现这个功能,我在考虑用字符串替换和正则表达式。

相关问题:

3 个回答

0

你需要用到的是 re 模块。

不过,你可能需要重新考虑一下你选择的分隔符。因为 $% 可能会有问题,因为 $ 在正则表达式中是一个特殊字符。这个决定还是在你,不过记得在你的模式中使用 '\\$' 或者 r'\$'(这是一个原始字符串。如果你在 Python 中做正则表达式,这个很有用)。

1
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
8

使用 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)

撰写回答