Skip to main content
 首页 » 编程设计

python之正则表达式查找并替换为字典

2025年05月04日39lori

我有一个由两部分组成的问题。最后,我尝试使用 regex 搜索 $"" 中包含的任何字符串,然后将其替换为字典中的值。这是我拥有的:

import re 
 
# Dictionary to use to replace with later 
myDict = {'hand_R_item':'hand_R_node', 'hand_L_item':'hand_L_node', 'hips_item':'hips_node', 'body_item':'body_node'} 
 
# String to process 
command = '''objs = [$"hand_R_item", $"hand_L_item", $"hips_item"] 
for obj in objs: 
    cmds.select(add = True) 
    cmds.parent(obj, $"body_item") 
''' 
 
# Find all instances of anything matching $"" 
regex = re.compile(r'\$\"[\w]*?\"') 
allMatches = re.findall(regex, command) 
 
# Replace matches with values from dict 
newCommand = command 
for match in allMatches: 
    newCommand = newCommand.replace(match, myDict.get(match[2:-1], '') ) 
print newCommand 

这将输出以下内容,这是想要的:

'objs = [hand_R_node, hand_L_node, hips_node] 
for obj in objs: 
    cmds.select(add = True) 
    cmds.parent(obj, body_node)' 

我的问题主要是看我是否以正确的方式处理这个问题:

  1. r'\$\"[\w]*?\"' 是最好的模式吗?我不太习惯使用正则表达式,所以我不知道我是否遗漏了任何陷阱!
  2. 是否有更有效的方法来替换所有内容而不是循环遍历正则表达式结果?我觉得可能有更优雅的方法。

请您参考如下方法:

你可以在这里直接使用re.sub。此外,在您的正则表达式中,您不需要转义引号。 \w 可以在字符类之外:

>>> d = {'hand_R_item':'hand_R_node', 'hand_L_item':'hand_L_node', 'hips_item':'hips_node', 'body_item':'body_node'} 
>>> reg = re.compile(r'\$"(\w*?)"') 
>>> command = '''objs = [$"hand_R_item", $"hand_L_item", $"hips_item"] 
... for obj in objs: 
...     cmds.select(add = True) 
...     cmds.parent(obj, $"body_item") 
... ''' 
>>>  
>>> # Replace the group 1, with corresponding value from dict 
>>> reg.sub(lambda m: d[m.group(1)], command) 
'objs = [hand_R_node, hand_L_node, hips_node]\nfor obj in objs:\n    cmds.select(add = True)\n    cmds.parent(obj, body_node)\n' 
>>>