我有像下面这样的文本块,我在那里寻找所有的出现;
data ...;
...
run;在哪里..。可以是任何类型的字符串模式。我只想找到这种情况的出现,如果模式不在C样式注释中,或者它被包装在另一个模式中,如下面所示。我要找出所有的事情;
data foo;
set bar;
run;但不是
%macro x();
data foo;
set bar;
run;
%mend;或
/* data foo;*/
/* set bar;*/
/* run;*/我有以下函数,它将在封装在注释或%macro ... %mend中时排除模式,但是它只是返回最后一次匹配,而不是每次发生。我如何调整这一点,以返回每一个匹配作为一个列表的列表,每块一个列表?提前谢谢。
s = """
/**
* @file
* @brief Description of the program
*/
/**
* @macro xyz
* @brief Description of the Macro
*/
%macro xyz();
data foo_nomatch;
set bar;
run;
%mend;
/**
* @data foo_matchme
* @brief Description of the DataStep
*/
data foo_matchme;
set bar;
run;
# Should Not Match
/**
* data foo_nomatch2;
* set bar;
* run;
*/
/**
* @datastep: foo2
* @brief: This is a description.
*/
# Should match as a 2nd match
data foo_matchme2;
set bar;
run;
"""
def datastep(s):
t1 = 'data'
t2 = 'run;'
t3 = ';'
e1 = re.escape('/**')
e2 = re.escape('*/')
e3 = re.escape('%macro')
e4 = re.escape('%mend')
return re.findall('%s.*%s|%s.*%s|(%s.*?%s)' %(e1,e2,e3,e4,t1,t2),s,re.DOTALL|re.IGNORECASE)
print(datastep(s))发布于 2017-05-06 10:02:17
使跳过子规则的.*-part不贪婪,即将'%s.*%s|%s.*%s|(%s.*?%s)'更改为'%s.*?%s|%s.*?%s|(%s.*?%s)'。
演示:
for match in datastep(s):
if match:
print(match)输出:
data foo_matchme;
set bar;
run;
data foo_matchme2;
set bar;
run;https://stackoverflow.com/questions/43818798
复制相似问题