I have a regex which will convert {{ expression }} into {% print expression %} when expression is {{ function() }} or {{ object.function() }} or arithmetic operation like {{ a+b }} but will not convert when it will get {{ var }} or {{ object.attribute }}.
The issue with regex I have is it convert string expression {{ "string" }} or {{ "function()" }} or {{ "{{ var}}" }} into {% print "string" %} or {% print "function()" %} or {% print "{% print var %}" %}
import re
def replacement(val):
content = val.group(1)
if re.match('^\s*[\w\.]+\s*$', content):
return "{{%s}}" % content
else:
return "{%% print %s %%}" % content
string_obj = """{{ var }} {{ object.var }} {{ func()}} {{ object.function() }} {{ a+b }} {{ "string" }} {{ "{{ var }}" }} {{ "function()" }} {{ "a+b" }}"""
print(re.sub("{{(\s*.*?\s*)}}", replacement, string_obj))
Output:
'{{ var }} {{ object.var }} {%print func()%} {% print object.function() %} {% print a+b %} {% print "string" %} {% print "{{ var }}" %} {% print "function()" %} {% print "a+b" %}'
The output what I want is:
'{{ var }} {{ object.var }} {%print func()%} {% print object.function() %} {% print a+b %} {{ "string" }} {{ "{{ var }}" }} {{ "function()" }} {{ "a+b" }}'
Note: The one condition here is expression in between {{ }} can have string expression like {{ "string" }} i.e. with double quotes or {{ 'string' }} i.e. with single quotes.
\win your character group. You can either add the double quotes there with\", or, don't use a regular expression and test whether"()"is inval.group(1)(and anything else like+-*/).