user2652620
user2652620

Reputation: 464

Replace variable in expression

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:

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 ?

Upvotes: 0

Views: 624

Answers (1)

Inbar Rose
Inbar Rose

Reputation: 43447

Well, the pattern you need is: r'\bvar\b', the \b is "border" which lets us define the full "string" we want to replace without replacing things like "variable"

However, upon testing your "expected" string, I found it had a mistake in it:

expected = ' ### + variable + avar + var[x] ' # <- this last 'var' should be ###

Anyway. Solution:

>>> import re
>>> re.sub(r'\bvar\b', '###', expr)
' ### + variable + avar + ###[x] + fun(###,variable) + fun2(variable, ###, var1) + fun3(variable,###)+ ###  -###/###+###*###*(###)'

Upvotes: 1

Related Questions