regex python在有方括号的地方拆分并替换[duplicate]

mgdq6dx1  于 2022-11-18  发布在  Python
关注(0)|答案(1)|浏览(111)

此问题在此处已有答案

How to use a variable inside a regular expression?(12个答案)
3天前关闭。
我想替换花括号中的单词。我搜索了一些类似的问题,但它们与我想要的不匹配。
我试过使用正则表达式。我的想法是首先拆分有空格的字符串,然后检查拆分列表中的每个值,并进一步用花括号拆分该值。然后我将检查该值是否在字典中。如果在字典中,我将替换它,如果不在字典中,我将添加其他单词。我很难得到它,我将感谢帮助。

zaqlnxep

zaqlnxep1#

请尝试:

import re

dicts = {"item1": "dog", "item2": "cat", "item4": "kindness"}

s = """This's my pet {item1|female donkey}. It was a gift from Mr {item3|David Smith}. Junior. I thank him for is {item4|humbleness}."""

pat = re.compile(r"\{([^|]+)\|([^}]+)}")
s = pat.sub(lambda g: dicts.get(g.group(1), g.group(2)), s)

print(s)

印刷品:

This's my pet dog. It was a gift from Mr David Smith. Junior. I thank him for is kindness.

编辑:如果没有提供默认项,您可以用途:

import re

dicts = {"item1": "dog", "item2": "cat", "item4": "kindness"}

s = """This's my pet {item1|female donkey}. It was a gift from Mr {item3|}. Junior. I thank him for is {item4|humbleness}."""

pat = re.compile(r"\{([^|]+)\|([^}]*)}")
s = pat.sub(lambda g: dicts.get(g.group(1), g.group(2).strip() or "N/A"), s)

print(s)

印刷品:

This's my pet dog. It was a gift from Mr N/A. Junior. I thank him for is kindness.

相关问题