正则表达式select not commented语句

2024-09-24 04:29:25 发布

您现在位置:Python中文网/ 问答频道 /正文

echo '<pre>'; print_r(1); echo '</pre>';  <- select this

 echo '<pre>'; print_r($temp); echo '</pre>';  <- select this without space

// echo '<pre>'; print_r($temp); echo '</pre>';  <- skip this



echo '<pre>'; print_r($temp3); echo '</pre>';  <- select this

print_r($temp1);  <- select this

// print_r($temp11);  <- skip this

    print_r($temp2);  <- select this without spaces

    if (true) {
        print_r($temp4);  <- select this without spaces

    }

我有一个打印语句的代码,我只需要选择非注释语句

这是正则表达式

^((?!\/\/\s?))(echo '<pre>';\s?)?(.+)?(print_r)(\.?)(\w+)?\((.+)?\);( echo '<\/pre>';)?

DEMO

如何跳过空格?' print_r($temp4);' 或者我如何改变regex使其工作?你知道吗


Tags: echospace语句thisselectpretempspaces
3条回答
import re

rgx = re.compile('^[ \t]*((echo|print_r).*;)', re.MULTILINE)
for line in rgx.finditer(code):
    print line.group(1)

# echo '<pre>'; print_r(1); echo '</pre>';
# echo '<pre>'; print_r($temp); echo '</pre>';
# echo '<pre>'; print_r($temp3); echo '</pre>';
# print_r($temp1);
# print_r($temp2);
# print_r($temp4);

如果有注释,这个正则表达式不会捕获行(//, @*, /*, <!--)否则它将捕获所有没有空格的内容,希望这能解决您的问题。你知道吗

([\n]|^)(?P<group>(?! *\/\/| *@\*| *\/\*| *<!--| *\\\*)([^\n]*?)(\S)(((?! *\/\/| *@\*| *\/\*| *<!--| *\\\*).)*))

可能是这样的:

^(?!\/\/) *(echo '<pre>';\s?)?(.+)?(print_r)(\.?)(\w+)?\((.+)?\);( echo '<\/pre>';)?

相关问题 更多 >