re.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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. 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 or just before the newline at
  29. the end of the string.
  30. "*" Matches 0 or more (greedy) repetitions of the preceding RE.
  31. Greedy means that it will match as many repetitions as possible.
  32. "+" Matches 1 or more (greedy) repetitions of the preceding RE.
  33. "?" Matches 0 or 1 (greedy) of the preceding RE.
  34. *?,+?,?? Non-greedy versions of the previous three special characters.
  35. {m,n} Matches from m to n repetitions of the preceding RE.
  36. {m,n}? Non-greedy version of the above.
  37. "\\" Either escapes special characters or signals a special sequence.
  38. [] Indicates a set of characters.
  39. A "^" as the first character indicates a complementing set.
  40. "|" A|B, creates an RE that will match either A or B.
  41. (...) Matches the RE inside the parentheses.
  42. The contents can be retrieved or matched later in the string.
  43. (?aiLmsux) Set the A, I, L, M, S, U, or X flag for the RE (see below).
  44. (?:...) Non-grouping version of regular parentheses.
  45. (?P<name>...) The substring matched by the group is accessible by name.
  46. (?P=name) Matches the text matched earlier by the group named name.
  47. (?#...) A comment; ignored.
  48. (?=...) Matches if ... matches next, but doesn't consume the string.
  49. (?!...) Matches if ... doesn't match next.
  50. (?<=...) Matches if preceded by ... (must be fixed length).
  51. (?<!...) Matches if not preceded by ... (must be fixed length).
  52. (?(id/name)yes|no) Matches yes pattern if the group with id/name matched,
  53. the (optional) no pattern otherwise.
  54. The special sequences consist of "\\" and a character from the list
  55. below. If the ordinary character is not on the list, then the
  56. resulting RE will match the second character.
  57. \number Matches the contents of the group of the same number.
  58. \A Matches only at the start of the string.
  59. \Z Matches only at the end of the string.
  60. \b Matches the empty string, but only at the start or end of a word.
  61. \B Matches the empty string, but not at the start or end of a word.
  62. \d Matches any decimal digit; equivalent to the set [0-9] in
  63. bytes patterns or string patterns with the ASCII flag.
  64. In string patterns without the ASCII flag, it will match the whole
  65. range of Unicode digits.
  66. \D Matches any non-digit character; equivalent to [^\d].
  67. \s Matches any whitespace character; equivalent to [ \t\n\r\f\v] in
  68. bytes patterns or string patterns with the ASCII flag.
  69. In string patterns without the ASCII flag, it will match the whole
  70. range of Unicode whitespace characters.
  71. \S Matches any non-whitespace character; equivalent to [^\s].
  72. \w Matches any alphanumeric character; equivalent to [a-zA-Z0-9_]
  73. in bytes patterns or string patterns with the ASCII flag.
  74. In string patterns without the ASCII flag, it will match the
  75. range of Unicode alphanumeric characters (letters plus digits
  76. plus underscore).
  77. With LOCALE, it will match the set [0-9_] plus characters defined
  78. as letters for the current locale.
  79. \W Matches the complement of \w.
  80. \\ Matches a literal backslash.
  81. This module exports the following functions:
  82. match Match a regular expression pattern to the beginning of a string.
  83. fullmatch Match a regular expression pattern to all of a string.
  84. search Search a string for the presence of a pattern.
  85. sub Substitute occurrences of a pattern found in a string.
  86. subn Same as sub, but also return the number of substitutions made.
  87. split Split a string by the occurrences of a pattern.
  88. findall Find all occurrences of a pattern in a string.
  89. finditer Return an iterator yielding a match object for each match.
  90. compile Compile a pattern into a RegexObject.
  91. purge Clear the regular expression cache.
  92. escape Backslash all non-alphanumerics in a string.
  93. Some of the functions in this module takes flags as optional parameters:
  94. A ASCII For string patterns, make \w, \W, \b, \B, \d, \D
  95. match the corresponding ASCII character categories
  96. (rather than the whole Unicode categories, which is the
  97. default).
  98. For bytes patterns, this flag is the only available
  99. behaviour and needn't be specified.
  100. I IGNORECASE Perform case-insensitive matching.
  101. L LOCALE Make \w, \W, \b, \B, dependent on the current locale.
  102. M MULTILINE "^" matches the beginning of lines (after a newline)
  103. as well as the string.
  104. "$" matches the end of lines (before a newline) as well
  105. as the end of the string.
  106. S DOTALL "." matches any character at all, including the newline.
  107. X VERBOSE Ignore whitespace and comments for nicer looking RE's.
  108. U UNICODE For compatibility only. Ignored for string patterns (it
  109. is the default), and forbidden for bytes patterns.
  110. This module also defines an exception 'error'.
  111. """
  112. import sys
  113. import sre_compile
  114. import sre_parse
  115. try:
  116. import _locale
  117. except ImportError:
  118. _locale = None
  119. # public symbols
  120. __all__ = [
  121. "match", "fullmatch", "search", "sub", "subn", "split",
  122. "findall", "finditer", "compile", "purge", "template", "escape",
  123. "error", "A", "I", "L", "M", "S", "X", "U",
  124. "ASCII", "IGNORECASE", "LOCALE", "MULTILINE", "DOTALL", "VERBOSE",
  125. "UNICODE",
  126. ]
  127. __version__ = "2.2.1"
  128. # flags
  129. A = ASCII = sre_compile.SRE_FLAG_ASCII # assume ascii "locale"
  130. I = IGNORECASE = sre_compile.SRE_FLAG_IGNORECASE # ignore case
  131. L = LOCALE = sre_compile.SRE_FLAG_LOCALE # assume current 8-bit locale
  132. U = UNICODE = sre_compile.SRE_FLAG_UNICODE # assume unicode "locale"
  133. M = MULTILINE = sre_compile.SRE_FLAG_MULTILINE # make anchors look for newline
  134. S = DOTALL = sre_compile.SRE_FLAG_DOTALL # make dot match newline
  135. X = VERBOSE = sre_compile.SRE_FLAG_VERBOSE # ignore whitespace and comments
  136. # sre extensions (experimental, don't rely on these)
  137. T = TEMPLATE = sre_compile.SRE_FLAG_TEMPLATE # disable backtracking
  138. DEBUG = sre_compile.SRE_FLAG_DEBUG # dump pattern after compilation
  139. # sre exception
  140. error = sre_compile.error
  141. # --------------------------------------------------------------------
  142. # public interface
  143. def match(pattern, string, flags=0):
  144. """Try to apply the pattern at the start of the string, returning
  145. a match object, or None if no match was found."""
  146. return _compile(pattern, flags).match(string)
  147. def fullmatch(pattern, string, flags=0):
  148. """Try to apply the pattern to all of the string, returning
  149. a match object, or None if no match was found."""
  150. return _compile(pattern, flags).fullmatch(string)
  151. def search(pattern, string, flags=0):
  152. """Scan through string looking for a match to the pattern, returning
  153. a match object, or None if no match was found."""
  154. return _compile(pattern, flags).search(string)
  155. def sub(pattern, repl, string, count=0, flags=0):
  156. """Return the string obtained by replacing the leftmost
  157. non-overlapping occurrences of the pattern in string by the
  158. replacement repl. repl can be either a string or a callable;
  159. if a string, backslash escapes in it are processed. If it is
  160. a callable, it's passed the match object and must return
  161. a replacement string to be used."""
  162. return _compile(pattern, flags).sub(repl, string, count)
  163. def subn(pattern, repl, string, count=0, flags=0):
  164. """Return a 2-tuple containing (new_string, number).
  165. new_string is the string obtained by replacing the leftmost
  166. non-overlapping occurrences of the pattern in the source
  167. string by the replacement repl. number is the number of
  168. substitutions that were made. repl can be either a string or a
  169. callable; if a string, backslash escapes in it are processed.
  170. If it is a callable, it's passed the match object and must
  171. return a replacement string to be used."""
  172. return _compile(pattern, flags).subn(repl, string, count)
  173. def split(pattern, string, maxsplit=0, flags=0):
  174. """Split the source string by the occurrences of the pattern,
  175. returning a list containing the resulting substrings. If
  176. capturing parentheses are used in pattern, then the text of all
  177. groups in the pattern are also returned as part of the resulting
  178. list. If maxsplit is nonzero, at most maxsplit splits occur,
  179. and the remainder of the string is returned as the final element
  180. of the list."""
  181. return _compile(pattern, flags).split(string, maxsplit)
  182. def findall(pattern, string, flags=0):
  183. """Return a list of all non-overlapping matches in the string.
  184. If one or more capturing groups are present in the pattern, return
  185. a list of groups; this will be a list of tuples if the pattern
  186. has more than one group.
  187. Empty matches are included in the result."""
  188. return _compile(pattern, flags).findall(string)
  189. def finditer(pattern, string, flags=0):
  190. """Return an iterator over all non-overlapping matches in the
  191. string. For each match, the iterator returns a match object.
  192. Empty matches are included in the result."""
  193. return _compile(pattern, flags).finditer(string)
  194. def compile(pattern, flags=0):
  195. "Compile a regular expression pattern, returning a pattern object."
  196. return _compile(pattern, flags)
  197. def purge():
  198. "Clear the regular expression caches"
  199. _cache.clear()
  200. _cache_repl.clear()
  201. def template(pattern, flags=0):
  202. "Compile a template pattern, returning a pattern object"
  203. return _compile(pattern, flags|T)
  204. _alphanum_str = frozenset(
  205. "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890")
  206. _alphanum_bytes = frozenset(
  207. b"_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890")
  208. def escape(pattern):
  209. """
  210. Escape all the characters in pattern except ASCII letters, numbers and '_'.
  211. """
  212. if isinstance(pattern, str):
  213. alphanum = _alphanum_str
  214. s = list(pattern)
  215. for i, c in enumerate(pattern):
  216. if c not in alphanum:
  217. if c == "\000":
  218. s[i] = "\\000"
  219. else:
  220. s[i] = "\\" + c
  221. return "".join(s)
  222. else:
  223. alphanum = _alphanum_bytes
  224. s = []
  225. esc = ord(b"\\")
  226. for c in pattern:
  227. if c in alphanum:
  228. s.append(c)
  229. else:
  230. if c == 0:
  231. s.extend(b"\\000")
  232. else:
  233. s.append(esc)
  234. s.append(c)
  235. return bytes(s)
  236. # --------------------------------------------------------------------
  237. # internals
  238. _cache = {}
  239. _cache_repl = {}
  240. _pattern_type = type(sre_compile.compile("", 0))
  241. _MAXCACHE = 512
  242. def _compile(pattern, flags):
  243. # internal: compile pattern
  244. try:
  245. p, loc = _cache[type(pattern), pattern, flags]
  246. if loc is None or loc == _locale.setlocale(_locale.LC_CTYPE):
  247. return p
  248. except KeyError:
  249. pass
  250. if isinstance(pattern, _pattern_type):
  251. if flags:
  252. raise ValueError(
  253. "cannot process flags argument with a compiled pattern")
  254. return pattern
  255. if not sre_compile.isstring(pattern):
  256. raise TypeError("first argument must be string or compiled pattern")
  257. p = sre_compile.compile(pattern, flags)
  258. if not (flags & DEBUG):
  259. if len(_cache) >= _MAXCACHE:
  260. _cache.clear()
  261. if p.flags & LOCALE:
  262. if not _locale:
  263. return p
  264. loc = _locale.setlocale(_locale.LC_CTYPE)
  265. else:
  266. loc = None
  267. _cache[type(pattern), pattern, flags] = p, loc
  268. return p
  269. def _compile_repl(repl, pattern):
  270. # internal: compile replacement pattern
  271. try:
  272. return _cache_repl[repl, pattern]
  273. except KeyError:
  274. pass
  275. p = sre_parse.parse_template(repl, pattern)
  276. if len(_cache_repl) >= _MAXCACHE:
  277. _cache_repl.clear()
  278. _cache_repl[repl, pattern] = p
  279. return p
  280. def _expand(pattern, match, template):
  281. # internal: match.expand implementation hook
  282. template = sre_parse.parse_template(template, pattern)
  283. return sre_parse.expand_template(template, match)
  284. def _subx(pattern, template):
  285. # internal: pattern.sub/subn implementation helper
  286. template = _compile_repl(template, pattern)
  287. if not template[0] and len(template[1]) == 1:
  288. # literal replacement
  289. return template[1][0]
  290. def filter(match, template=template):
  291. return sre_parse.expand_template(template, match)
  292. return filter
  293. # register myself for pickling
  294. import copyreg
  295. def _pickle(p):
  296. return _compile, (p.pattern, p.flags)
  297. copyreg.pickle(_pattern_type, _pickle, _compile)
  298. # --------------------------------------------------------------------
  299. # experimental stuff (see python-dev discussions for details)
  300. class Scanner:
  301. def __init__(self, lexicon, flags=0):
  302. from sre_constants import BRANCH, SUBPATTERN
  303. self.lexicon = lexicon
  304. # combine phrases into a compound pattern
  305. p = []
  306. s = sre_parse.Pattern()
  307. s.flags = flags
  308. for phrase, action in lexicon:
  309. gid = s.opengroup()
  310. p.append(sre_parse.SubPattern(s, [
  311. (SUBPATTERN, (gid, sre_parse.parse(phrase, flags))),
  312. ]))
  313. s.closegroup(gid, p[-1])
  314. p = sre_parse.SubPattern(s, [(BRANCH, (None, p))])
  315. self.scanner = sre_compile.compile(p)
  316. def scan(self, string):
  317. result = []
  318. append = result.append
  319. match = self.scanner.scanner(string).match
  320. i = 0
  321. while True:
  322. m = match()
  323. if not m:
  324. break
  325. j = m.end()
  326. if i == j:
  327. break
  328. action = self.lexicon[m.lastindex-1][1]
  329. if callable(action):
  330. self.match = m
  331. action = action(self, m.group())
  332. if action is not None:
  333. append(action)
  334. i = j
  335. return result, string[i:]