sre.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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 ([email protected]).
  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. r"""Support for regular expressions (RE).
  17. This module provides regular expression matching operations similar to
  18. those found in Perl. It supports both 8-bit and Unicode strings; both
  19. the pattern and the strings being processed can contain null bytes and
  20. characters outside the US ASCII range.
  21. Regular expressions can contain both special and ordinary characters.
  22. Most ordinary characters, like "A", "a", or "0", are the simplest
  23. regular expressions; they simply match themselves. You can
  24. concatenate ordinary characters, so last matches the string 'last'.
  25. The special characters are:
  26. "." Matches any character except a newline.
  27. "^" Matches the start of the string.
  28. "$" Matches the end of the string.
  29. "*" Matches 0 or more (greedy) repetitions of the preceding RE.
  30. Greedy means that it will match as many repetitions as possible.
  31. "+" Matches 1 or more (greedy) repetitions of the preceding RE.
  32. "?" Matches 0 or 1 (greedy) of the preceding RE.
  33. *?,+?,?? Non-greedy versions of the previous three special characters.
  34. {m,n} Matches from m to n repetitions of the preceding RE.
  35. {m,n}? Non-greedy version of the above.
  36. "\\" Either escapes special characters or signals a special sequence.
  37. [] Indicates a set of characters.
  38. A "^" as the first character indicates a complementing set.
  39. "|" A|B, creates an RE that will match either A or B.
  40. (...) Matches the RE inside the parentheses.
  41. The contents can be retrieved or matched later in the string.
  42. (?iLmsux) Set the I, L, M, S, U, or X flag for the RE (see below).
  43. (?:...) Non-grouping version of regular parentheses.
  44. (?P<name>...) The substring matched by the group is accessible by name.
  45. (?P=name) Matches the text matched earlier by the group named name.
  46. (?#...) A comment; ignored.
  47. (?=...) Matches if ... matches next, but doesn't consume the string.
  48. (?!...) Matches if ... doesn't match next.
  49. The special sequences consist of "\\" and a character from the list
  50. below. If the ordinary character is not on the list, then the
  51. resulting RE will match the second character.
  52. \number Matches the contents of the group of the same number.
  53. \A Matches only at the start of the string.
  54. \Z Matches only at the end of the string.
  55. \b Matches the empty string, but only at the start or end of a word.
  56. \B Matches the empty string, but not at the start or end of a word.
  57. \d Matches any decimal digit; equivalent to the set [0-9].
  58. \D Matches any non-digit character; equivalent to the set [^0-9].
  59. \s Matches any whitespace character; equivalent to [ \t\n\r\f\v].
  60. \S Matches any non-whitespace character; equiv. to [^ \t\n\r\f\v].
  61. \w Matches any alphanumeric character; equivalent to [a-zA-Z0-9_].
  62. With LOCALE, it will match the set [0-9_] plus characters defined
  63. as letters for the current locale.
  64. \W Matches the complement of \w.
  65. \\ Matches a literal backslash.
  66. This module exports the following functions:
  67. match Match a regular expression pattern to the beginning of a string.
  68. search Search a string for the presence of a pattern.
  69. sub Substitute occurrences of a pattern found in a string.
  70. subn Same as sub, but also return the number of substitutions made.
  71. split Split a string by the occurrences of a pattern.
  72. findall Find all occurrences of a pattern in a string.
  73. compile Compile a pattern into a RegexObject.
  74. purge Clear the regular expression cache.
  75. escape Backslash all non-alphanumerics in a string.
  76. Some of the functions in this module takes flags as optional parameters:
  77. I IGNORECASE Perform case-insensitive matching.
  78. L LOCALE Make \w, \W, \b, \B, dependent on the current locale.
  79. M MULTILINE "^" matches the beginning of lines as well as the string.
  80. "$" matches the end of lines as well as the string.
  81. S DOTALL "." matches any character at all, including the newline.
  82. X VERBOSE Ignore whitespace and comments for nicer looking RE's.
  83. U UNICODE Make \w, \W, \b, \B, dependent on the Unicode locale.
  84. This module also defines an exception 'error'.
  85. """
  86. import sys
  87. import sre_compile
  88. import sre_parse
  89. # public symbols
  90. __all__ = [ "match", "search", "sub", "subn", "split", "findall",
  91. "compile", "purge", "template", "escape", "I", "L", "M", "S", "X",
  92. "U", "IGNORECASE", "LOCALE", "MULTILINE", "DOTALL", "VERBOSE",
  93. "UNICODE", "error" ]
  94. __version__ = "2.2.1"
  95. # flags
  96. I = IGNORECASE = sre_compile.SRE_FLAG_IGNORECASE # ignore case
  97. L = LOCALE = sre_compile.SRE_FLAG_LOCALE # assume current 8-bit locale
  98. U = UNICODE = sre_compile.SRE_FLAG_UNICODE # assume unicode locale
  99. M = MULTILINE = sre_compile.SRE_FLAG_MULTILINE # make anchors look for newline
  100. S = DOTALL = sre_compile.SRE_FLAG_DOTALL # make dot match newline
  101. X = VERBOSE = sre_compile.SRE_FLAG_VERBOSE # ignore whitespace and comments
  102. # sre extensions (experimental, don't rely on these)
  103. T = TEMPLATE = sre_compile.SRE_FLAG_TEMPLATE # disable backtracking
  104. DEBUG = sre_compile.SRE_FLAG_DEBUG # dump pattern after compilation
  105. # sre exception
  106. error = sre_compile.error
  107. # --------------------------------------------------------------------
  108. # public interface
  109. def match(pattern, string, flags=0):
  110. """Try to apply the pattern at the start of the string, returning
  111. a match object, or None if no match was found."""
  112. return _compile(pattern, flags).match(string)
  113. def search(pattern, string, flags=0):
  114. """Scan through string looking for a match to the pattern, returning
  115. a match object, or None if no match was found."""
  116. return _compile(pattern, flags).search(string)
  117. def sub(pattern, repl, string, count=0):
  118. """Return the string obtained by replacing the leftmost
  119. non-overlapping occurrences of the pattern in string by the
  120. replacement repl. repl can be either a string or a callable;
  121. if a callable, it's passed the match object and must return
  122. a replacement string to be used."""
  123. return _compile(pattern, 0).sub(repl, string, count)
  124. def subn(pattern, repl, string, count=0):
  125. """Return a 2-tuple containing (new_string, number).
  126. new_string is the string obtained by replacing the leftmost
  127. non-overlapping occurrences of the pattern in the source
  128. string by the replacement repl. number is the number of
  129. substitutions that were made. repl can be either a string or a
  130. callable; if a callable, it's passed the match object and must
  131. return a replacement string to be used."""
  132. return _compile(pattern, 0).subn(repl, string, count)
  133. def split(pattern, string, maxsplit=0):
  134. """Split the source string by the occurrences of the pattern,
  135. returning a list containing the resulting substrings."""
  136. return _compile(pattern, 0).split(string, maxsplit)
  137. def findall(pattern, string, flags=0):
  138. """Return a list of all non-overlapping matches in the string.
  139. If one or more groups are present in the pattern, return a
  140. list of groups; this will be a list of tuples if the pattern
  141. has more than one group.
  142. Empty matches are included in the result."""
  143. return _compile(pattern, flags).findall(string)
  144. if sys.hexversion >= 0x02020000:
  145. __all__.append("finditer")
  146. def finditer(pattern, string, flags=0):
  147. """Return an iterator over all non-overlapping matches in the
  148. string. For each match, the iterator returns a match object.
  149. Empty matches are included in the result."""
  150. return _compile(pattern, flags).finditer(string)
  151. def compile(pattern, flags=0):
  152. "Compile a regular expression pattern, returning a pattern object."
  153. return _compile(pattern, flags)
  154. def purge():
  155. "Clear the regular expression cache"
  156. _cache.clear()
  157. _cache_repl.clear()
  158. def template(pattern, flags=0):
  159. "Compile a template pattern, returning a pattern object"
  160. return _compile(pattern, flags|T)
  161. def escape(pattern):
  162. "Escape all non-alphanumeric characters in pattern."
  163. s = list(pattern)
  164. for i in range(len(pattern)):
  165. c = pattern[i]
  166. if not ("a" <= c <= "z" or "A" <= c <= "Z" or "0" <= c <= "9"):
  167. if c == "\000":
  168. s[i] = "\\000"
  169. else:
  170. s[i] = "\\" + c
  171. return pattern[:0].join(s)
  172. # --------------------------------------------------------------------
  173. # internals
  174. _cache = {}
  175. _cache_repl = {}
  176. _pattern_type = type(sre_compile.compile("", 0))
  177. _MAXCACHE = 100
  178. def _compile(*key):
  179. # internal: compile pattern
  180. cachekey = (type(key[0]),) + key
  181. p = _cache.get(cachekey)
  182. if p is not None:
  183. return p
  184. pattern, flags = key
  185. if isinstance(pattern, _pattern_type):
  186. return pattern
  187. if not sre_compile.isstring(pattern):
  188. raise TypeError, "first argument must be string or compiled pattern"
  189. try:
  190. p = sre_compile.compile(pattern, flags)
  191. except error, v:
  192. raise error, v # invalid expression
  193. if len(_cache) >= _MAXCACHE:
  194. _cache.clear()
  195. _cache[cachekey] = p
  196. return p
  197. def _compile_repl(*key):
  198. # internal: compile replacement pattern
  199. p = _cache_repl.get(key)
  200. if p is not None:
  201. return p
  202. repl, pattern = key
  203. try:
  204. p = sre_parse.parse_template(repl, pattern)
  205. except error, v:
  206. raise error, v # invalid expression
  207. if len(_cache_repl) >= _MAXCACHE:
  208. _cache_repl.clear()
  209. _cache_repl[key] = p
  210. return p
  211. def _expand(pattern, match, template):
  212. # internal: match.expand implementation hook
  213. template = sre_parse.parse_template(template, pattern)
  214. return sre_parse.expand_template(template, match)
  215. def _subx(pattern, template):
  216. # internal: pattern.sub/subn implementation helper
  217. template = _compile_repl(template, pattern)
  218. if not template[0] and len(template[1]) == 1:
  219. # literal replacement
  220. return template[1][0]
  221. def filter(match, template=template):
  222. return sre_parse.expand_template(template, match)
  223. return filter
  224. # register myself for pickling
  225. import copy_reg
  226. def _pickle(p):
  227. return _compile, (p.pattern, p.flags)
  228. copy_reg.pickle(_pattern_type, _pickle, _compile)
  229. # --------------------------------------------------------------------
  230. # experimental stuff (see python-dev discussions for details)
  231. class Scanner:
  232. def __init__(self, lexicon, flags=0):
  233. from sre_constants import BRANCH, SUBPATTERN
  234. self.lexicon = lexicon
  235. # combine phrases into a compound pattern
  236. p = []
  237. s = sre_parse.Pattern()
  238. s.flags = flags
  239. for phrase, action in lexicon:
  240. p.append(sre_parse.SubPattern(s, [
  241. (SUBPATTERN, (len(p)+1, sre_parse.parse(phrase, flags))),
  242. ]))
  243. p = sre_parse.SubPattern(s, [(BRANCH, (None, p))])
  244. s.groups = len(p)
  245. self.scanner = sre_compile.compile(p)
  246. def scan(self, string):
  247. result = []
  248. append = result.append
  249. match = self.scanner.scanner(string).match
  250. i = 0
  251. while 1:
  252. m = match()
  253. if not m:
  254. break
  255. j = m.end()
  256. if i == j:
  257. break
  258. action = self.lexicon[m.lastindex-1][1]
  259. if callable(action):
  260. self.match = m
  261. action = action(self, m.group())
  262. if action is not None:
  263. append(action)
  264. i = j
  265. return result, string[i:]