【发布时间】:2018-12-19 23:30:25
【问题描述】:
我知道有一种方法可以替换所有匹配某种模式的实例,如下所示:re.sub(r'x', 'y', string)。
但是有没有办法用字典中最后一个字符的值对应的值替换所有实例,如#a、#b?
dict = {'a': '1', 'b': 2', ... }
所以abc#bcd#ae 变成abc2cd1e 等等。
【问题讨论】:
标签: python regex pattern-matching
我知道有一种方法可以替换所有匹配某种模式的实例,如下所示:re.sub(r'x', 'y', string)。
但是有没有办法用字典中最后一个字符的值对应的值替换所有实例,如#a、#b?
dict = {'a': '1', 'b': 2', ... }
所以abc#bcd#ae 变成abc2cd1e 等等。
【问题讨论】:
标签: python regex pattern-matching
re.sub 的第二个参数(替换任何匹配项)可以是可调用的。如果是这样,则为每个匹配项使用单个参数(匹配对象)调用它,并将其结果替换为字符串。所以你可以这样做:
d = {'a': 'A', 'b': 'B'}
s = '#a #b and #c'
def replace_it(m):
return d.get(m.group('key'), m.group(0))
print re.sub('#(?P<key>[a-zA-Z]+)', replace_it, s)
【讨论】:
您可以替换字符串中找到的所有匹配项:
mydict = {'a':'1', 'b':'2'}
mystr = '#a#b'
for k, v in mydict.items():
mystr = mystr.replace('#' + k, v)
【讨论】:
如果您知道要替换的确切内容,则不需要正则表达式。这些更适合您寻找模式,而不是完全匹配。 string.replace 应该可以解决这个问题。
string = "a#acbb#bd"
dictionary = {'a':'1', 'b':'2'}
newstring1 = string.replace('#a', dictionary['a'])
newstring = newstring1.replace('#b', dictionary['b'])
print(newstring)
>>>a1cbb2d
【讨论】: