在Python中,我想要一对像这样的:
模式:
abc, def
ghi, jkl
mno, xyz
这个想法是:给定一个字符串,我想从模式中搜索任何模式 p 的出现,当我找到匹配项时,我想用其对应项替换它。
例如:
- 这是一个 abcwer 字符串
这是一个
def
wer字符串(替换的字符串)
很多匹配 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/