python - 将模式与模式列表中的对应项进行匹配

标签 python regex string replace

在Python中,我想要一对像这样的:

模式:

abc, def
ghi, jkl
mno, xyz

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

例如:

  • 这是一个 abcwer 字符串
  • 这是一个defwer字符串(替换的字符串)

  • 很多匹配 abc-ghi-mno

  • 很多匹配项def-jkl-xyz (替换的字符串)

到目前为止,我正在用空字符串替换模式匹配,这是我的做法:

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 执行此操作的方法是什么?

最佳答案

您可以使用 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'

关于python - 将模式与模式列表中的对应项进行匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25576963/

相关文章:

c++ - 转义字符串中的反斜杠?

python - 如何创建只有一个帖子的页面?

使用字符串进行Python对象匹配

c++ - 在 C++ 中从前缀到字符位置创建一个新字符串

sql - 在 Redshift SQL 中从数组中提取值

c - 如何使用 mpc 解析器定义标准数学符号

java - 将html标签格式化为字符串java

python - 从numpy数组中选择指定的月份日期(日期时间对象)

python - OSX Pillow 不兼容的库版本 libtiff.5.dylib 和 libjpeg.8.dylib

python - 如何正确使用 scikit-learn 的高斯过程进行 2D 输入、1D 输出回归?