I'm using regexp to find and replace a variable in python expression in string format. I don't want the 'var' replaced to be the part of another function or variable name. (I banned the solution using if 'var' in expr and expr.replace("var", etc.)).
So, I check the previous characters (allowed) and the following characters(allowed) with the following regexp:
pattern = re.compile(r'(^var)(?=\+|\-|\*|\/| |$)|(?<=\+|\=|\[|\-|\*|\/|,| |\()var(?=\+|\-|\*|\/|$| |,|\))')
ô_O, it seems to be complicated but it works on the following test, replacing 'var' by '###'
expr = ' var + variable + avar + var[x] + fun(var,variable) + fun2(variable, var, var1) + fun3(variable,var)+ var -var/var+var*var*(var)'
expected = ' ### + variable + avar + var[x] + fun(###,variable) + fun2(variable, ###, var1) + fun3(variable,###)+ ### -###/###+###*###*(###)'
I use regexp:
- to ckeck if 'var' is in expression
- to replace 'var' in expression
- to check if 'var' is not in expression after being replaced.
if pattern.search(expr):
new_expr = re.sub(pattern, '###', expr)
assert not pattern.search(new_expr), 'Replace failed'
I use the code a lot of time and I'm wondering if something simpler/faster exists ?
varinvar[x]- is that intentional, or a typo?