Python re regex sub letters not arused in quotes and not if they match specific word including regex group / match

Python re regex sub letters not surrounded in quotes and not if they match specific word including regex group / match

我需要子字母不包含在引号中,如果它们将单词 TODAY 与特定字符串匹配,其中一部分包含匹配组,例如

import re
import string

s = 'AB+B+" HELLO"+TODAY()/C* 100'
x = re.sub(r'\"[^"]*\"|\bTODAY\b|([A-Z]+)', r'a2num("\g<0>")', s)

print (x)

预期输出:

'a2num("AB")+a2num("B")+" HELLO"+TODAY()/a2num("C")* 100'

实际输出:

'a2num("AB")+a2num("B")+a2num("" HELLO"")+a2num("TODAY")()/a2num("C")* 100'

我快到了,但它不遵守引号规则或 TODAY 单词规则,我知道该字符串没有任何意义,但这只是对正则表达式的严格测试

您的正则表达式方法是正确的,但您需要在 re.sub

中使用 lambda 函数
>>> s = 'AB+B+" HELLO"+TODAY()/C* 100'
>>> rs = re.sub(r'"[^"]*"|\bTODAY\b|\b([A-Z]+)\b',
...     lambda m: 'a2num("' + m.group(1) + '")' if m.group(1) else m.group(), s)
>>> print (rs)

a2num("AB")+a2num("B")+" HELLO"+TODAY()/a2num("C")* 100

Code Demo