用 python 中的表达式替换整个单词 忽略算术运算符

replace whole word from expression in python ignore arithmetic operator

我有一个字符串表达式,如 "(addtwo*decimal*p_cost)/(cost+density)"
我只想替换成本,但它替换了 p_cost 以及 - p_"replaced value"。我已经尝试过单词边界但没有运气请帮忙。

expr = '(addtwo*decimal*p_cost)/(cost+density)'

expr = string.replace(expr, r"\b%s\b" % str(' cost '), str(3)) not doing anything.

使用正则表达式。

import re
expr = '(addtwo*decimal*p_cost)/(cost+density)'
print(re.sub(r"\bcost\b", "3", expr))

输出:

(addtwo*decimal*p_cost)/(3+density)
import re

expr = r'(addtwo*decimal*p_cost)/(cost+density)'

expr2 = re.sub("(?<![_])cost(?![_])","COST", expr)
print(expr2)

在搜索词(本例中为cost)之前((?<![_]))和之后((?![_]))的方括号中插入所有禁止替换搜索词的字符正则表达式模式字符串。