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

时间:2015-10-04 08:57:56

标签: python regex dictionary

我有两个问题。最后,我尝试使用$""搜索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. 是否有更有效的方法来替换所有内容而不是循环使用正则表达式结果?我觉得可能会有更优雅的方法。

1 个答案:

答案 0 :(得分:1)

您可以在这里直接使用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'
>>>