You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

sre.py 8.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. #
  2. # Secret Labs' Regular Expression Engine
  3. #
  4. # re-compatible interface for the sre matching engine
  5. #
  6. # Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved.
  7. #
  8. # This version of the SRE library can be redistributed under CNRI's
  9. # Python 1.6 license. For any other use, please contact Secret Labs
  10. # AB (info@pythonware.com).
  11. #
  12. # Portions of this engine have been developed in cooperation with
  13. # CNRI. Hewlett-Packard provided funding for 1.6 integration and
  14. # other compatibility work.
  15. #
  16. import sre_compile
  17. import sre_parse
  18. # public symbols
  19. __all__ = [ "match", "search", "sub", "subn", "split", "findall",
  20. "compile", "purge", "template", "escape", "I", "L", "M", "S", "X",
  21. "U", "IGNORECASE", "LOCALE", "MULTILINE", "DOTALL", "VERBOSE",
  22. "UNICODE", "error" ]
  23. __version__ = "2.1b2"
  24. # this module works under 1.5.2 and later. don't use string methods
  25. import string
  26. # flags
  27. I = IGNORECASE = sre_compile.SRE_FLAG_IGNORECASE # ignore case
  28. L = LOCALE = sre_compile.SRE_FLAG_LOCALE # assume current 8-bit locale
  29. U = UNICODE = sre_compile.SRE_FLAG_UNICODE # assume unicode locale
  30. M = MULTILINE = sre_compile.SRE_FLAG_MULTILINE # make anchors look for newline
  31. S = DOTALL = sre_compile.SRE_FLAG_DOTALL # make dot match newline
  32. X = VERBOSE = sre_compile.SRE_FLAG_VERBOSE # ignore whitespace and comments
  33. # sre extensions (experimental, don't rely on these)
  34. T = TEMPLATE = sre_compile.SRE_FLAG_TEMPLATE # disable backtracking
  35. DEBUG = sre_compile.SRE_FLAG_DEBUG # dump pattern after compilation
  36. # sre exception
  37. error = sre_compile.error
  38. # --------------------------------------------------------------------
  39. # public interface
  40. def match(pattern, string, flags=0):
  41. """Try to apply the pattern at the start of the string, returning
  42. a match object, or None if no match was found."""
  43. return _compile(pattern, flags).match(string)
  44. def search(pattern, string, flags=0):
  45. """Scan through string looking for a match to the pattern, returning
  46. a match object, or None if no match was found."""
  47. return _compile(pattern, flags).search(string)
  48. def sub(pattern, repl, string, count=0):
  49. """Return the string obtained by replacing the leftmost
  50. non-overlapping occurrences of the pattern in string by the
  51. replacement repl"""
  52. return _compile(pattern, 0).sub(repl, string, count)
  53. def subn(pattern, repl, string, count=0):
  54. """Return a 2-tuple containing (new_string, number).
  55. new_string is the string obtained by replacing the leftmost
  56. non-overlapping occurrences of the pattern in the source
  57. string by the replacement repl. number is the number of
  58. substitutions that were made."""
  59. return _compile(pattern, 0).subn(repl, string, count)
  60. def split(pattern, string, maxsplit=0):
  61. """Split the source string by the occurrences of the pattern,
  62. returning a list containing the resulting substrings."""
  63. return _compile(pattern, 0).split(string, maxsplit)
  64. def findall(pattern, string, maxsplit=0):
  65. """Return a list of all non-overlapping matches in the string.
  66. If one or more groups are present in the pattern, return a
  67. list of groups; this will be a list of tuples if the pattern
  68. has more than one group.
  69. Empty matches are included in the result."""
  70. return _compile(pattern, 0).findall(string, maxsplit)
  71. def compile(pattern, flags=0):
  72. "Compile a regular expression pattern, returning a pattern object."
  73. return _compile(pattern, flags)
  74. def purge():
  75. "Clear the regular expression cache"
  76. _cache.clear()
  77. _cache_repl.clear()
  78. def template(pattern, flags=0):
  79. "Compile a template pattern, returning a pattern object"
  80. return _compile(pattern, flags|T)
  81. def escape(pattern):
  82. "Escape all non-alphanumeric characters in pattern."
  83. s = list(pattern)
  84. for i in range(len(pattern)):
  85. c = pattern[i]
  86. if not ("a" <= c <= "z" or "A" <= c <= "Z" or "0" <= c <= "9"):
  87. if c == "\000":
  88. s[i] = "\\000"
  89. else:
  90. s[i] = "\\" + c
  91. return _join(s, pattern)
  92. # --------------------------------------------------------------------
  93. # internals
  94. _cache = {}
  95. _cache_repl = {}
  96. _MAXCACHE = 100
  97. def _join(seq, sep):
  98. # internal: join into string having the same type as sep
  99. return string.join(seq, sep[:0])
  100. def _compile(*key):
  101. # internal: compile pattern
  102. p = _cache.get(key)
  103. if p is not None:
  104. return p
  105. pattern, flags = key
  106. if type(pattern) not in sre_compile.STRING_TYPES:
  107. return pattern
  108. try:
  109. p = sre_compile.compile(pattern, flags)
  110. except error, v:
  111. raise error, v # invalid expression
  112. if len(_cache) >= _MAXCACHE:
  113. _cache.clear()
  114. _cache[key] = p
  115. return p
  116. def _compile_repl(*key):
  117. # internal: compile replacement pattern
  118. p = _cache_repl.get(key)
  119. if p is not None:
  120. return p
  121. repl, pattern = key
  122. try:
  123. p = sre_parse.parse_template(repl, pattern)
  124. except error, v:
  125. raise error, v # invalid expression
  126. if len(_cache_repl) >= _MAXCACHE:
  127. _cache_repl.clear()
  128. _cache_repl[key] = p
  129. return p
  130. def _expand(pattern, match, template):
  131. # internal: match.expand implementation hook
  132. template = sre_parse.parse_template(template, pattern)
  133. return sre_parse.expand_template(template, match)
  134. def _sub(pattern, template, string, count=0):
  135. # internal: pattern.sub implementation hook
  136. return _subn(pattern, template, string, count)[0]
  137. def _subn(pattern, template, string, count=0):
  138. # internal: pattern.subn implementation hook
  139. if callable(template):
  140. filter = template
  141. else:
  142. template = _compile_repl(template, pattern)
  143. def filter(match, template=template):
  144. return sre_parse.expand_template(template, match)
  145. n = i = 0
  146. s = []
  147. append = s.append
  148. c = pattern.scanner(string)
  149. while not count or n < count:
  150. m = c.search()
  151. if not m:
  152. break
  153. b, e = m.span()
  154. if i < b:
  155. append(string[i:b])
  156. append(filter(m))
  157. i = e
  158. n = n + 1
  159. append(string[i:])
  160. return _join(s, string[:0]), n
  161. def _split(pattern, string, maxsplit=0):
  162. # internal: pattern.split implementation hook
  163. n = i = 0
  164. s = []
  165. append = s.append
  166. extend = s.extend
  167. c = pattern.scanner(string)
  168. g = pattern.groups
  169. while not maxsplit or n < maxsplit:
  170. m = c.search()
  171. if not m:
  172. break
  173. b, e = m.span()
  174. if b == e:
  175. if i >= len(string):
  176. break
  177. continue
  178. append(string[i:b])
  179. if g and b != e:
  180. extend(list(m.groups()))
  181. i = e
  182. n = n + 1
  183. append(string[i:])
  184. return s
  185. # register myself for pickling
  186. import copy_reg
  187. def _pickle(p):
  188. return _compile, (p.pattern, p.flags)
  189. copy_reg.pickle(type(_compile("", 0)), _pickle, _compile)
  190. # --------------------------------------------------------------------
  191. # experimental stuff (see python-dev discussions for details)
  192. class Scanner:
  193. def __init__(self, lexicon):
  194. from sre_constants import BRANCH, SUBPATTERN
  195. self.lexicon = lexicon
  196. # combine phrases into a compound pattern
  197. p = []
  198. s = sre_parse.Pattern()
  199. for phrase, action in lexicon:
  200. p.append(sre_parse.SubPattern(s, [
  201. (SUBPATTERN, (len(p), sre_parse.parse(phrase))),
  202. ]))
  203. p = sre_parse.SubPattern(s, [(BRANCH, (None, p))])
  204. s.groups = len(p)
  205. self.scanner = sre_compile.compile(p)
  206. def scan(self, string):
  207. result = []
  208. append = result.append
  209. match = self.scanner.match
  210. i = 0
  211. while 1:
  212. m = match(string, i)
  213. if not m:
  214. break
  215. j = m.end()
  216. if i == j:
  217. break
  218. action = self.lexicon[m.lastindex][1]
  219. if callable(action):
  220. self.match = m
  221. action = action(self, m.group())
  222. if action is not None:
  223. append(action)
  224. i = j
  225. return result, string[i:]