2015-11-09 29 views
-1
while something: 
    do something; 
    do somethingelse; 
    do thelastthing; 
continue with other statements.. 

我試圖創建一個只匹配while循環中最後一條語句的正則表達式。我會如何去做這件事?查找序列正則表達式的最後一次出現

+0

在什麼語言?大多數語言都提供了獲取最後一次事件的方法,或者至少提供了所有可以訪問最後一個事件的事件的列表。 – Marty

+0

使用python正則表達式 – user3044396

+0

你想要匹配什麼文本? –

回答

0

您應該提供更多信息以獲得更清晰的答案。 爲什麼不用一個變量控制循環,讓我們說「c」,將它用作「進/不進去」變量? 例子:

c = 0 
while c == 0: 
if thisistrue: 
    c = 1 
else: 
    dosomething 
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;" 

ideone demo

相關問題