while something:
do something;
do somethingelse;
do thelastthing;
continue with other statements..
我正在尝试创建一个仅与while循环中的最后一个语句匹配的正则表达式。我该怎么做呢?
答案 0 :(得分:0)
您应该提供更多信息以获得更清晰的答案。 为什么不用变量控制循环,让我们说“c”,将它用作“进入/不进入”变量? 例如:
c = 0
while c == 0:
if thisistrue:
c = 1
else:
dosomething
答案 1 :(得分:0)
如your previous question中所述,您可以使用
捕获while循环的缩进级别^([ \t]*) while\b
然后将每一行与相同的缩进级别\1
加上匹配至少一个空格。
\n\1 [ \t]+ (?P<last_statement>.*)
<强>代码强>
import re
while_loop = re.compile(r'''
#while statement (group 1 captures the indentation)
^([ \t]*) while\b .* $
#code
(?:
#comments with any indentation
(?:
\s*?
\n [ \t]* [#].*
)*
#Optional else lines
(?:
\s*?
\n\1 else [ \t]* .* $
)?
#following lines with more indentation
\s*?
\n\1 [ \t]+ (?P<last_statement>.*)
)*
\n?
''', re.MULTILINE | re.VERBOSE)
test_str = r'''
while something:
do something;
do somethingelse;
do thelastthing;
continue with other statements..
'''
# Loop matches
m = 0
for match in while_loop.finditer(test_str):
m += 1
print( 'Match #%s [%s:%s]\nLast statement [%s:%s]:\t"%s"'
%(m, match.start(), match.end(), match.start("last_statement"),
match.end("last_statement"), match.group("last_statement")))
if m == 0:
print("NO MATCH")
<强>输出强>
Match #1 [1:91]
Last statement [74:90]: "do thelastthing;"