fork download
  1. # http://stackoverflow.com/q/33600768/5290909
  2. # Match last statement in Python while loop
  3. import re
  4.  
  5. while_loop = re.compile(r'''
  6. #while statement (group 1 captures the indentation)
  7. ^([ \t]*) while\b .* $
  8.  
  9. #code
  10. (?:
  11. #comments with any indentation
  12. (?:
  13. \s*?
  14. \n [ \t]* [#].*
  15. )*
  16.  
  17. #Optional else lines
  18. (?:
  19. \s*?
  20. \n\1 else [ \t]* .* $
  21. )?
  22.  
  23. #following lines with more indentation
  24. \s*?
  25. \n\1 [ \t]+ (?P<last_statement>.*)
  26. )*
  27.  
  28. \n?
  29. ''', re.MULTILINE | re.VERBOSE)
  30.  
  31.  
  32. test_str = r'''
  33. while something:
  34. do something;
  35. do somethingelse;
  36. do thelastthing;
  37. continue with other statements..
  38. '''
  39.  
  40.  
  41. # Loop matches
  42. m = 0
  43. for match in while_loop.finditer(test_str):
  44. m += 1
  45. print( 'Match #%s [%s:%s]\nLast statement [%s:%s]:\t"%s"'
  46. %(m, match.start(), match.end(), match.start("last_statement"),
  47. match.end("last_statement"), match.group("last_statement")))
  48.  
  49. if m == 0:
  50. print("NO MATCH")
Success #stdin #stdout 0.01s 8968KB
stdin
Standard input is empty
stdout
Match #1 [1:91]
Last statement [74:90]:	"do thelastthing;"