且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python 中的多个特定正则表达式替换

更新时间:2023-02-17 21:30:19

import re

def multiple_replace(dict, text):
  # Create a regular expression  from the dictionary keys
  regex = re.compile(r'(%s)' % "|".join(dict.keys()))
  return regex.sub(lambda mo: dict[
      [ k for k in dict if
      re.search(k, mo.string[mo.start():mo.end()])
      ][0]], text)

d = { r'ba[rz]*' : 'bar', '<' : '[' }
s = 'barzzzzzz <'

print multiple_replace(d, s)

给予:

bar [