我有Smarty模板代码。使用Python re,我希望匹配整个if条件,如果它在新行上拆分。目标是删除所有条件。
{if true eq isset( $username ) and false eq $is_logged and false}
{if true eq isset( $username )
and false eq $is_logged and false}
{if true eq isset( $username ) and $boolLoggedIn}
Hello {$username}
{/if}
{if true eq isset( $username )}
{assign var=username value=$fname}
{/if}
我尝试使用下面的正则表达式,但只有当条件在一行时才匹配。
{(if|/if)(.)*(?<=})
答案 0 :(得分:1)
不是使用.
来匹配所有内容(并且它与新行不匹配,至少在默认情况下是这样),更好的方法可能是匹配所有 - 除了 - 近括号:[^}]
。你也可以简单地简化正则表达式。
import re
TEXT = '''
{if true eq isset( $username ) and false eq $is_logged and false}
{if true eq isset( $username )
and false eq $is_logged and false}
{if true eq isset( $username ) and $boolLoggedIn}
Hello {$username}
{/if}
{if true eq isset( $username )}
{assign var=username value=$fname}
{/if}
'''
rgx = re.compile(r'{/?if[^}]*}')
for m in rgx.findall(TEXT):
print()
print(m)
答案 1 :(得分:0)