PageRenderTime 53ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2/re.py

https://bitbucket.org/kcr/pypy
Python | 324 lines | 294 code | 5 blank | 25 comment | 13 complexity | 5e220eaba3023d949ee3bf829cc7dab2 MD5 | raw file
Possible License(s): Apache-2.0
  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. (?iLmsux) Set the 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].
  63. \D Matches any non-digit character; equivalent to the set [^0-9].
  64. \s Matches any whitespace character; equivalent to [ \t\n\r\f\v].
  65. \S Matches any non-whitespace character; equiv. to [^ \t\n\r\f\v].
  66. \w Matches any alphanumeric character; equivalent to [a-zA-Z0-9_].
  67. With LOCALE, it will match the set [0-9_] plus characters defined
  68. as letters for the current locale.
  69. \W Matches the complement of \w.
  70. \\ Matches a literal backslash.
  71. This module exports the following functions:
  72. match Match a regular expression pattern to the beginning of a string.
  73. search Search a string for the presence of a pattern.
  74. sub Substitute occurrences of a pattern found in a string.
  75. subn Same as sub, but also return the number of substitutions made.
  76. split Split a string by the occurrences of a pattern.
  77. findall Find all occurrences of a pattern in a string.
  78. finditer Return an iterator yielding a match object for each match.
  79. compile Compile a pattern into a RegexObject.
  80. purge Clear the regular expression cache.
  81. escape Backslash all non-alphanumerics in a string.
  82. Some of the functions in this module takes flags as optional parameters:
  83. I IGNORECASE Perform case-insensitive matching.
  84. L LOCALE Make \w, \W, \b, \B, dependent on the current locale.
  85. M MULTILINE "^" matches the beginning of lines (after a newline)
  86. as well as the string.
  87. "$" matches the end of lines (before a newline) as well
  88. as the end of the string.
  89. S DOTALL "." matches any character at all, including the newline.
  90. X VERBOSE Ignore whitespace and comments for nicer looking RE's.
  91. U UNICODE Make \w, \W, \b, \B, dependent on the Unicode locale.
  92. This module also defines an exception 'error'.
  93. """
  94. import sys
  95. import sre_compile
  96. import sre_parse
  97. # public symbols
  98. __all__ = [ "match", "search", "sub", "subn", "split", "findall",
  99. "compile", "purge", "template", "escape", "I", "L", "M", "S", "X",
  100. "U", "IGNORECASE", "LOCALE", "MULTILINE", "DOTALL", "VERBOSE",
  101. "UNICODE", "error" ]
  102. __version__ = "2.2.1"
  103. # flags
  104. I = IGNORECASE = sre_compile.SRE_FLAG_IGNORECASE # ignore case
  105. L = LOCALE = sre_compile.SRE_FLAG_LOCALE # assume current 8-bit locale
  106. U = UNICODE = sre_compile.SRE_FLAG_UNICODE # assume unicode locale
  107. M = MULTILINE = sre_compile.SRE_FLAG_MULTILINE # make anchors look for newline
  108. S = DOTALL = sre_compile.SRE_FLAG_DOTALL # make dot match newline
  109. X = VERBOSE = sre_compile.SRE_FLAG_VERBOSE # ignore whitespace and comments
  110. # sre extensions (experimental, don't rely on these)
  111. T = TEMPLATE = sre_compile.SRE_FLAG_TEMPLATE # disable backtracking
  112. DEBUG = sre_compile.SRE_FLAG_DEBUG # dump pattern after compilation
  113. # sre exception
  114. error = sre_compile.error
  115. # --------------------------------------------------------------------
  116. # public interface
  117. def match(pattern, string, flags=0):
  118. """Try to apply the pattern at the start of the string, returning
  119. a match object, or None if no match was found."""
  120. return _compile(pattern, flags).match(string)
  121. def search(pattern, string, flags=0):
  122. """Scan through string looking for a match to the pattern, returning
  123. a match object, or None if no match was found."""
  124. return _compile(pattern, flags).search(string)
  125. def sub(pattern, repl, string, count=0, flags=0):
  126. """Return the string obtained by replacing the leftmost
  127. non-overlapping occurrences of the pattern in string by the
  128. replacement repl. repl can be either a string or a callable;
  129. if a string, backslash escapes in it are processed. If it is
  130. a callable, it's passed the match object and must return
  131. a replacement string to be used."""
  132. return _compile(pattern, flags).sub(repl, string, count)
  133. def subn(pattern, repl, string, count=0, flags=0):
  134. """Return a 2-tuple containing (new_string, number).
  135. new_string is the string obtained by replacing the leftmost
  136. non-overlapping occurrences of the pattern in the source
  137. string by the replacement repl. number is the number of
  138. substitutions that were made. repl can be either a string or a
  139. callable; if a string, backslash escapes in it are processed.
  140. If it is a callable, it's passed the match object and must
  141. return a replacement string to be used."""
  142. return _compile(pattern, flags).subn(repl, string, count)
  143. def split(pattern, string, maxsplit=0, flags=0):
  144. """Split the source string by the occurrences of the pattern,
  145. returning a list containing the resulting substrings."""
  146. return _compile(pattern, flags).split(string, maxsplit)
  147. def findall(pattern, string, flags=0):
  148. """Return a list of all non-overlapping matches in the string.
  149. If one or more groups are present in the pattern, return a
  150. list of groups; this will be a list of tuples if the pattern
  151. has more than one group.
  152. Empty matches are included in the result."""
  153. return _compile(pattern, flags).findall(string)
  154. if sys.hexversion >= 0x02020000:
  155. __all__.append("finditer")
  156. def finditer(pattern, string, flags=0):
  157. """Return an iterator over all non-overlapping matches in the
  158. string. For each match, the iterator returns a match object.
  159. Empty matches are included in the result."""
  160. return _compile(pattern, flags).finditer(string)
  161. def compile(pattern, flags=0):
  162. "Compile a regular expression pattern, returning a pattern object."
  163. return _compile(pattern, flags)
  164. def purge():
  165. "Clear the regular expression cache"
  166. _cache.clear()
  167. _cache_repl.clear()
  168. def template(pattern, flags=0):
  169. "Compile a template pattern, returning a pattern object"
  170. return _compile(pattern, flags|T)
  171. _alphanum = frozenset(
  172. "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
  173. def escape(pattern):
  174. "Escape all non-alphanumeric characters in pattern."
  175. s = list(pattern)
  176. alphanum = _alphanum
  177. for i, c in enumerate(pattern):
  178. if c not in alphanum:
  179. if c == "\000":
  180. s[i] = "\\000"
  181. else:
  182. s[i] = "\\" + c
  183. return pattern[:0].join(s)
  184. # --------------------------------------------------------------------
  185. # internals
  186. _cache = {}
  187. _cache_repl = {}
  188. _pattern_type = type(sre_compile.compile("", 0))
  189. _MAXCACHE = 100
  190. def _compile(*key):
  191. # internal: compile pattern
  192. cachekey = (type(key[0]),) + key
  193. p = _cache.get(cachekey)
  194. if p is not None:
  195. return p
  196. pattern, flags = key
  197. if isinstance(pattern, _pattern_type):
  198. if flags:
  199. raise ValueError('Cannot process flags argument with a compiled pattern')
  200. return pattern
  201. if not sre_compile.isstring(pattern):
  202. raise TypeError, "first argument must be string or compiled pattern"
  203. try:
  204. p = sre_compile.compile(pattern, flags)
  205. except error, v:
  206. raise error, v # invalid expression
  207. if len(_cache) >= _MAXCACHE:
  208. _cache.clear()
  209. _cache[cachekey] = p
  210. return p
  211. def _compile_repl(*key):
  212. # internal: compile replacement pattern
  213. p = _cache_repl.get(key)
  214. if p is not None:
  215. return p
  216. repl, pattern = key
  217. try:
  218. p = sre_parse.parse_template(repl, pattern)
  219. except error, v:
  220. raise error, v # invalid expression
  221. if len(_cache_repl) >= _MAXCACHE:
  222. _cache_repl.clear()
  223. _cache_repl[key] = p
  224. return p
  225. def _expand(pattern, match, template):
  226. # internal: match.expand implementation hook
  227. template = sre_parse.parse_template(template, pattern)
  228. return sre_parse.expand_template(template, match)
  229. def _subx(pattern, template):
  230. # internal: pattern.sub/subn implementation helper
  231. template = _compile_repl(template, pattern)
  232. if not template[0] and len(template[1]) == 1:
  233. # literal replacement
  234. return template[1][0]
  235. def filter(match, template=template):
  236. return sre_parse.expand_template(template, match)
  237. return filter
  238. # register myself for pickling
  239. import copy_reg
  240. def _pickle(p):
  241. return _compile, (p.pattern, p.flags)
  242. copy_reg.pickle(_pattern_type, _pickle, _compile)
  243. # --------------------------------------------------------------------
  244. # experimental stuff (see python-dev discussions for details)
  245. class Scanner:
  246. def __init__(self, lexicon, flags=0):
  247. from sre_constants import BRANCH, SUBPATTERN
  248. self.lexicon = lexicon
  249. # combine phrases into a compound pattern
  250. p = []
  251. s = sre_parse.Pattern()
  252. s.flags = flags
  253. for phrase, action in lexicon:
  254. p.append(sre_parse.SubPattern(s, [
  255. (SUBPATTERN, (len(p)+1, sre_parse.parse(phrase, flags))),
  256. ]))
  257. s.groups = len(p)+1
  258. p = sre_parse.SubPattern(s, [(BRANCH, (None, p))])
  259. self.scanner = sre_compile.compile(p)
  260. def scan(self, string):
  261. result = []
  262. append = result.append
  263. match = self.scanner.scanner(string).match
  264. i = 0
  265. while 1:
  266. m = match()
  267. if not m:
  268. break
  269. j = m.end()
  270. if i == j:
  271. break
  272. action = self.lexicon[m.lastindex-1][1]
  273. if hasattr(action, '__call__'):
  274. self.match = m
  275. action = action(self, m.group())
  276. if action is not None:
  277. append(action)
  278. i = j
  279. return result, string[i:]