__init__.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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) The letters set the corresponding flags defined 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 Pattern object.
  91. purge Clear the regular expression cache.
  92. escape Backslash all non-alphanumerics in a string.
  93. Each function other than purge and escape can take an optional 'flags' argument
  94. consisting of one or more of the following module constants, joined by "|".
  95. A, L, and U are mutually exclusive.
  96. A ASCII For string patterns, make \w, \W, \b, \B, \d, \D
  97. match the corresponding ASCII character categories
  98. (rather than the whole Unicode categories, which is the
  99. default).
  100. For bytes patterns, this flag is the only available
  101. behaviour and needn't be specified.
  102. I IGNORECASE Perform case-insensitive matching.
  103. L LOCALE Make \w, \W, \b, \B, dependent on the current locale.
  104. M MULTILINE "^" matches the beginning of lines (after a newline)
  105. as well as the string.
  106. "$" matches the end of lines (before a newline) as well
  107. as the end of the string.
  108. S DOTALL "." matches any character at all, including the newline.
  109. X VERBOSE Ignore whitespace and comments for nicer looking RE's.
  110. U UNICODE For compatibility only. Ignored for string patterns (it
  111. is the default), and forbidden for bytes patterns.
  112. This module also defines an exception 'error'.
  113. """
  114. import enum
  115. from . import _compiler, _parser
  116. import functools
  117. import _sre
  118. # public symbols
  119. __all__ = [
  120. "match", "fullmatch", "search", "sub", "subn", "split",
  121. "findall", "finditer", "compile", "purge", "template", "escape",
  122. "error", "Pattern", "Match", "A", "I", "L", "M", "S", "X", "U",
  123. "ASCII", "IGNORECASE", "LOCALE", "MULTILINE", "DOTALL", "VERBOSE",
  124. "UNICODE", "NOFLAG", "RegexFlag",
  125. ]
  126. __version__ = "2.2.1"
  127. @enum.global_enum
  128. @enum._simple_enum(enum.IntFlag, boundary=enum.KEEP)
  129. class RegexFlag:
  130. NOFLAG = 0
  131. ASCII = A = _compiler.SRE_FLAG_ASCII # assume ascii "locale"
  132. IGNORECASE = I = _compiler.SRE_FLAG_IGNORECASE # ignore case
  133. LOCALE = L = _compiler.SRE_FLAG_LOCALE # assume current 8-bit locale
  134. UNICODE = U = _compiler.SRE_FLAG_UNICODE # assume unicode "locale"
  135. MULTILINE = M = _compiler.SRE_FLAG_MULTILINE # make anchors look for newline
  136. DOTALL = S = _compiler.SRE_FLAG_DOTALL # make dot match newline
  137. VERBOSE = X = _compiler.SRE_FLAG_VERBOSE # ignore whitespace and comments
  138. # sre extensions (experimental, don't rely on these)
  139. TEMPLATE = T = _compiler.SRE_FLAG_TEMPLATE # unknown purpose, deprecated
  140. DEBUG = _compiler.SRE_FLAG_DEBUG # dump pattern after compilation
  141. __str__ = object.__str__
  142. _numeric_repr_ = hex
  143. # sre exception
  144. error = _compiler.error
  145. # --------------------------------------------------------------------
  146. # public interface
  147. def match(pattern, string, flags=0):
  148. """Try to apply the pattern at the start of the string, returning
  149. a Match object, or None if no match was found."""
  150. return _compile(pattern, flags).match(string)
  151. def fullmatch(pattern, string, flags=0):
  152. """Try to apply the pattern to all of the string, returning
  153. a Match object, or None if no match was found."""
  154. return _compile(pattern, flags).fullmatch(string)
  155. def search(pattern, string, flags=0):
  156. """Scan through string looking for a match to the pattern, returning
  157. a Match object, or None if no match was found."""
  158. return _compile(pattern, flags).search(string)
  159. def sub(pattern, repl, string, count=0, flags=0):
  160. """Return the string obtained by replacing the leftmost
  161. non-overlapping occurrences of the pattern in string by the
  162. replacement repl. repl can be either a string or a callable;
  163. if a string, backslash escapes in it are processed. If it is
  164. a callable, it's passed the Match object and must return
  165. a replacement string to be used."""
  166. return _compile(pattern, flags).sub(repl, string, count)
  167. def subn(pattern, repl, string, count=0, flags=0):
  168. """Return a 2-tuple containing (new_string, number).
  169. new_string is the string obtained by replacing the leftmost
  170. non-overlapping occurrences of the pattern in the source
  171. string by the replacement repl. number is the number of
  172. substitutions that were made. repl can be either a string or a
  173. callable; if a string, backslash escapes in it are processed.
  174. If it is a callable, it's passed the Match object and must
  175. return a replacement string to be used."""
  176. return _compile(pattern, flags).subn(repl, string, count)
  177. def split(pattern, string, maxsplit=0, flags=0):
  178. """Split the source string by the occurrences of the pattern,
  179. returning a list containing the resulting substrings. If
  180. capturing parentheses are used in pattern, then the text of all
  181. groups in the pattern are also returned as part of the resulting
  182. list. If maxsplit is nonzero, at most maxsplit splits occur,
  183. and the remainder of the string is returned as the final element
  184. of the list."""
  185. return _compile(pattern, flags).split(string, maxsplit)
  186. def findall(pattern, string, flags=0):
  187. """Return a list of all non-overlapping matches in the string.
  188. If one or more capturing groups are present in the pattern, return
  189. a list of groups; this will be a list of tuples if the pattern
  190. has more than one group.
  191. Empty matches are included in the result."""
  192. return _compile(pattern, flags).findall(string)
  193. def finditer(pattern, string, flags=0):
  194. """Return an iterator over all non-overlapping matches in the
  195. string. For each match, the iterator returns a Match object.
  196. Empty matches are included in the result."""
  197. return _compile(pattern, flags).finditer(string)
  198. def compile(pattern, flags=0):
  199. "Compile a regular expression pattern, returning a Pattern object."
  200. return _compile(pattern, flags)
  201. def purge():
  202. "Clear the regular expression caches"
  203. _cache.clear()
  204. _cache2.clear()
  205. _compile_template.cache_clear()
  206. def template(pattern, flags=0):
  207. "Compile a template pattern, returning a Pattern object, deprecated"
  208. import warnings
  209. warnings.warn("The re.template() function is deprecated "
  210. "as it is an undocumented function "
  211. "without an obvious purpose. "
  212. "Use re.compile() instead.",
  213. DeprecationWarning)
  214. with warnings.catch_warnings():
  215. warnings.simplefilter("ignore", DeprecationWarning) # warn just once
  216. return _compile(pattern, flags|T)
  217. # SPECIAL_CHARS
  218. # closing ')', '}' and ']'
  219. # '-' (a range in character set)
  220. # '&', '~', (extended character set operations)
  221. # '#' (comment) and WHITESPACE (ignored) in verbose mode
  222. _special_chars_map = {i: '\\' + chr(i) for i in b'()[]{}?*+-|^$\\.&~# \t\n\r\v\f'}
  223. def escape(pattern):
  224. """
  225. Escape special characters in a string.
  226. """
  227. if isinstance(pattern, str):
  228. return pattern.translate(_special_chars_map)
  229. else:
  230. pattern = str(pattern, 'latin1')
  231. return pattern.translate(_special_chars_map).encode('latin1')
  232. Pattern = type(_compiler.compile('', 0))
  233. Match = type(_compiler.compile('', 0).match(''))
  234. # --------------------------------------------------------------------
  235. # internals
  236. # Use the fact that dict keeps the insertion order.
  237. # _cache2 uses the simple FIFO policy which has better latency.
  238. # _cache uses the LRU policy which has better hit rate.
  239. _cache = {} # LRU
  240. _cache2 = {} # FIFO
  241. _MAXCACHE = 512
  242. _MAXCACHE2 = 256
  243. assert _MAXCACHE2 < _MAXCACHE
  244. def _compile(pattern, flags):
  245. # internal: compile pattern
  246. if isinstance(flags, RegexFlag):
  247. flags = flags.value
  248. try:
  249. return _cache2[type(pattern), pattern, flags]
  250. except KeyError:
  251. pass
  252. key = (type(pattern), pattern, flags)
  253. # Item in _cache should be moved to the end if found.
  254. p = _cache.pop(key, None)
  255. if p is None:
  256. if isinstance(pattern, Pattern):
  257. if flags:
  258. raise ValueError(
  259. "cannot process flags argument with a compiled pattern")
  260. return pattern
  261. if not _compiler.isstring(pattern):
  262. raise TypeError("first argument must be string or compiled pattern")
  263. if flags & T:
  264. import warnings
  265. warnings.warn("The re.TEMPLATE/re.T flag is deprecated "
  266. "as it is an undocumented flag "
  267. "without an obvious purpose. "
  268. "Don't use it.",
  269. DeprecationWarning)
  270. p = _compiler.compile(pattern, flags)
  271. if flags & DEBUG:
  272. return p
  273. if len(_cache) >= _MAXCACHE:
  274. # Drop the least recently used item.
  275. # next(iter(_cache)) is known to have linear amortized time,
  276. # but it is used here to avoid a dependency from using OrderedDict.
  277. # For the small _MAXCACHE value it doesn't make much of a difference.
  278. try:
  279. del _cache[next(iter(_cache))]
  280. except (StopIteration, RuntimeError, KeyError):
  281. pass
  282. # Append to the end.
  283. _cache[key] = p
  284. if len(_cache2) >= _MAXCACHE2:
  285. # Drop the oldest item.
  286. try:
  287. del _cache2[next(iter(_cache2))]
  288. except (StopIteration, RuntimeError, KeyError):
  289. pass
  290. _cache2[key] = p
  291. return p
  292. @functools.lru_cache(_MAXCACHE)
  293. def _compile_template(pattern, repl):
  294. # internal: compile replacement pattern
  295. return _sre.template(pattern, _parser.parse_template(repl, pattern))
  296. # register myself for pickling
  297. import copyreg
  298. def _pickle(p):
  299. return _compile, (p.pattern, p.flags)
  300. copyreg.pickle(Pattern, _pickle, _compile)
  301. # --------------------------------------------------------------------
  302. # experimental stuff (see python-dev discussions for details)
  303. class Scanner:
  304. def __init__(self, lexicon, flags=0):
  305. from ._constants import BRANCH, SUBPATTERN
  306. if isinstance(flags, RegexFlag):
  307. flags = flags.value
  308. self.lexicon = lexicon
  309. # combine phrases into a compound pattern
  310. p = []
  311. s = _parser.State()
  312. s.flags = flags
  313. for phrase, action in lexicon:
  314. gid = s.opengroup()
  315. p.append(_parser.SubPattern(s, [
  316. (SUBPATTERN, (gid, 0, 0, _parser.parse(phrase, flags))),
  317. ]))
  318. s.closegroup(gid, p[-1])
  319. p = _parser.SubPattern(s, [(BRANCH, (None, p))])
  320. self.scanner = _compiler.compile(p)
  321. def scan(self, string):
  322. result = []
  323. append = result.append
  324. match = self.scanner.scanner(string).match
  325. i = 0
  326. while True:
  327. m = match()
  328. if not m:
  329. break
  330. j = m.end()
  331. if i == j:
  332. break
  333. action = self.lexicon[m.lastindex-1][1]
  334. if callable(action):
  335. self.match = m
  336. action = action(self, m.group())
  337. if action is not None:
  338. append(action)
  339. i = j
  340. return result, string[i:]