fork download
  1. import re
  2.  
  3. test = """import (
  4. "github.com/user/qrt"
  5.  
  6. "fmt"
  7.  
  8. "github.com/user/zyx"
  9. )
  10.  
  11. import "abcdef"
  12.  
  13. import "abzdef"
  14. """
  15.  
  16. BEGIN = 1
  17. IMPORT = 2
  18. DESCENT = 3
  19.  
  20.  
  21. class Lexer(object):
  22. def __init__(self, text):
  23. self._rx = re.compile(r'(import|".*?"|\(|\))')
  24. self._text = text
  25.  
  26. def __iter__(self):
  27. for m in self._rx.finditer(self._text):
  28. yield m.group(1)
  29.  
  30.  
  31. class RecursiveDescent(object):
  32. state = BEGIN
  33.  
  34. def __init__(self, lexer):
  35. self._lexer = lexer
  36.  
  37. def __iter__(self):
  38. for token in self._lexer:
  39. if self.state == BEGIN:
  40. if token != 'import':
  41. # Beginning of the program most likely
  42. raise StopIteration
  43. self.state = IMPORT
  44. elif self.state == IMPORT:
  45. if token == '(':
  46. self.state = DESCENT
  47. else:
  48. self.state = BEGIN
  49. yield token
  50. elif self.state == DESCENT:
  51. if token == ')':
  52. self.state = BEGIN
  53. else:
  54. yield token
  55.  
  56. for path in RecursiveDescent(Lexer(test)):
  57. print(path)
  58.  
Success #stdin #stdout 0.02s 9984KB
stdin
Standard input is empty
stdout
"github.com/user/qrt"
"fmt"
"github.com/user/zyx"
"abcdef"
"abzdef"