Skip to content Skip to sidebar Skip to footer

Regex To Exclude String And Attribute Within Expression

I have a regex which will convert {{ expression }} into {% print expression %} when expression is {{ function() }} or {{ object.function() }} or arithmetic operation like {{ a+b }

Solution 1:

Code

For prettier printing I just strip the whitespace at beginning and end. It just simplifies the regex, too.

import re

defreplacement(val):
    content = val.group(1).strip()
    if re.match('^\w[^\.\(\+\*\/\-\|]*\.?\w[^\.\(\+\*\/\-\|]*$', content):
        return"{{ %s }}" % content
    else:
        return"{%% print %s %%}" % content

defmaskString(templateString):
    stringChars = ['"', "'"]
    a = 0
    start = None
    maskedList = []
    while a < len(templateString):
        l = templateString[a]
        if l in stringChars and start isNoneand a-1 >=0and templateString[a-1] != '\\':
            start = {'l' : l, 's' : a}
        elif start isnotNoneand l is start['l'] and a-1 >=0and templateString[a-1] != '\\':
            start['e'] = a + 1
            stringToMask = templateString[start['s']:start['e']]
            templateString = templateString[:start['s']] + ("_" * len(stringToMask)) + templateString[start['e']:]
            maskedList.append(stringToMask)
            start = None
        a += 1return (templateString, maskedList)

defunmaskString(templateString, maskedList):
    for string in maskedList:
        templateString = templateString.replace("_" * len(string), string,1)
    return templateString

deftemplateMatcher(templateString):
    p = re.compile('("[^"]*)"')
    templateString, maskedList = maskString(templateString)
    templateString = re.sub("{{(\s*.*?\s*)}}", replacement, templateString)
    return unmaskString(templateString, maskedList)

string_obj = """{{ var }} {{ object.var }} {{ func()}} {{ object.function() }} {{ a+b }} {{ "string" }} {{ "{{ var }}" }} {{ "function()" }} {{ "a+b" }}"""
string_obj_2 = """{{ a+b*c-d/100}} {{ 1 * 2 }} {{ 20/10 }} {{ 5-4 }}"""
string_obj_3 = """{{ "another {{ mask" }} {{ func() }}, {{ a+b }} , {{ "string with \\""|filter }}"""print(templateMatcher(string_obj))
print(templateMatcher(string_obj_2))
print(templateMatcher(string_obj_3))

Added an advanced masking for the strings so "\"" and '"' will be recognized as string, assuming that a variable could never consists only of _. Strings start and endcharacter are in the variable stringChars. So if you don't like the ' just remove it from there.

Output

{{ var }} {{ object.var }} {% printfunc() %} {% print object.function() %} {% print a+b %} {{ "string" }} {{ "{{ var }}" }} {{ "function()" }} {{ "a+b" }}
{% print a+b*c-d/100 %} {% print1 * 2 %} {% print20/10 %} {% print5-4 %}
{{ "another {{ mask" }} {% printfunc() %}, {% print a+b %} , {% print"string with \""|filter %}

Post a Comment for "Regex To Exclude String And Attribute Within Expression"