Python Regex匹配源代码中新行结尾的文本

时间:2018-05-26 00:37:37

标签: python regex

我有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)(.)*(?<=})

小提琴: https://regex101.com/r/dVTgla/2

2 个答案:

答案 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)

试试这个。

({\/?if[\s\S]*(?<=}))

.*无法正常工作的原因是因为它捕获了所有内容但行终止符。查看documentation here