从模式列表中匹配模式到对应模式

时间:2014-08-29 22:13:47

标签: python regex string replace

在Python中,我希望有这样一对:

模式:

abc, def
ghi, jkl
mno, xyz

这个想法是:给定一个字符串,我想从模式中搜索任何模式p的出现,当我找到匹配时,我想用它的对应物替换它。

例如:

  • 这是一个abcwer字符串
  • 这是一个def字符串(replaced string)

  • 很多比赛abc-ghi-mno

  • 很多匹配def-jkl-xyz (replaced string)

现在升级,我用空字符串替换模式匹配,这就是我这样做的方式:

regExps = [ re.compile(re.escape(p), re.IGNORECASE) for p in patterns ]

def cleanseName(dirName, name):
# please ignore dirName here since I have just put here a snippet of the code
    old = name
    new = ""
    for regExp in regExps:
        if regExp.search(old):
            new = regExp.sub("", old).strip()
            old = new
    if new != "":
        new = old
        print("replaced string: %s" % new)

那么,我怎么能在这里替换一对字符串呢? pythonic这样做的方式是什么?

2 个答案:

答案 0 :(得分:2)

您可以使用功能接受版re.sub

来支持重叠字符串
import re

substitutions = {
    "abc": "def",
    "def": "ghi",
    "ghi": "jkl",
    "jkl": "mno",
    "mno": "pqr"
}

def match_to_substitution(match):
    return substitutions[match.group()]

string = "abc def ghi jkl mno"

substitute_finder = re.compile("|".join(map(re.escape, substitutions)))

substitute_finder.sub(match_to_substitution, string)
#>>> 'def ghi jkl mno pqr'

答案 1 :(得分:0)

patterns = [('abc','def'),('ghi','jkl'),('mno','xyz')]

def cleanse_name(name, patterns):
    for from_,to in patterns:
        name = re.sub(re.escape(from_), to, name, flags=re.I)
    print(name)

cleanse_name("abcghimno Smith", patterns)
# defjklxyz Smith

这就是你要找的东西吗?