re.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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. import sre_compile
  116. import sre_parse
  117. import functools
  118. try:
  119. import _locale
  120. except ImportError:
  121. _locale = None
  122. # public symbols
  123. __all__ = [
  124. "match", "fullmatch", "search", "sub", "subn", "split",
  125. "findall", "finditer", "compile", "purge", "template", "escape",
  126. "error", "Pattern", "Match", "A", "I", "L", "M", "S", "X", "U",
  127. "ASCII", "IGNORECASE", "LOCALE", "MULTILINE", "DOTALL", "VERBOSE",
  128. "UNICODE",
  129. ]
  130. __version__ = "2.2.1"
  131. class RegexFlag(enum.IntFlag):
  132. ASCII = A = sre_compile.SRE_FLAG_ASCII # assume ascii "locale"
  133. IGNORECASE = I = sre_compile.SRE_FLAG_IGNORECASE # ignore case
  134. LOCALE = L = sre_compile.SRE_FLAG_LOCALE # assume current 8-bit locale
  135. UNICODE = U = sre_compile.SRE_FLAG_UNICODE # assume unicode "locale"
  136. MULTILINE = M = sre_compile.SRE_FLAG_MULTILINE # make anchors look for newline
  137. DOTALL = S = sre_compile.SRE_FLAG_DOTALL # make dot match newline
  138. VERBOSE = X = sre_compile.SRE_FLAG_VERBOSE # ignore whitespace and comments
  139. # sre extensions (experimental, don't rely on these)
  140. TEMPLATE = T = sre_compile.SRE_FLAG_TEMPLATE # disable backtracking
  141. DEBUG = sre_compile.SRE_FLAG_DEBUG # dump pattern after compilation
  142. def __repr__(self):
  143. if self._name_ is not None:
  144. return f're.{self._name_}'
  145. value = self._value_
  146. members = []
  147. negative = value < 0
  148. if negative:
  149. value = ~value
  150. for m in self.__class__:
  151. if value & m._value_:
  152. value &= ~m._value_
  153. members.append(f're.{m._name_}')
  154. if value:
  155. members.append(hex(value))
  156. res = '|'.join(members)
  157. if negative:
  158. if len(members) > 1:
  159. res = f'~({res})'
  160. else:
  161. res = f'~{res}'
  162. return res
  163. __str__ = object.__str__
  164. globals().update(RegexFlag.__members__)
  165. # sre exception
  166. error = sre_compile.error
  167. # --------------------------------------------------------------------
  168. # public interface
  169. def match(pattern, string, flags=0):
  170. """Try to apply the pattern at the start of the string, returning
  171. a Match object, or None if no match was found."""
  172. return _compile(pattern, flags).match(string)
  173. def fullmatch(pattern, string, flags=0):
  174. """Try to apply the pattern to all of the string, returning
  175. a Match object, or None if no match was found."""
  176. return _compile(pattern, flags).fullmatch(string)
  177. def search(pattern, string, flags=0):
  178. """Scan through string looking for a match to the pattern, returning
  179. a Match object, or None if no match was found."""
  180. return _compile(pattern, flags).search(string)
  181. def sub(pattern, repl, string, count=0, flags=0):
  182. """Return the string obtained by replacing the leftmost
  183. non-overlapping occurrences of the pattern in string by the
  184. replacement repl. repl can be either a string or a callable;
  185. if a string, backslash escapes in it are processed. If it is
  186. a callable, it's passed the Match object and must return
  187. a replacement string to be used."""
  188. return _compile(pattern, flags).sub(repl, string, count)
  189. def subn(pattern, repl, string, count=0, flags=0):
  190. """Return a 2-tuple containing (new_string, number).
  191. new_string is the string obtained by replacing the leftmost
  192. non-overlapping occurrences of the pattern in the source
  193. string by the replacement repl. number is the number of
  194. substitutions that were made. repl can be either a string or a
  195. callable; if a string, backslash escapes in it are processed.
  196. If it is a callable, it's passed the Match object and must
  197. return a replacement string to be used."""
  198. return _compile(pattern, flags).subn(repl, string, count)
  199. def split(pattern, string, maxsplit=0, flags=0):
  200. """Split the source string by the occurrences of the pattern,
  201. returning a list containing the resulting substrings. If
  202. capturing parentheses are used in pattern, then the text of all
  203. groups in the pattern are also returned as part of the resulting
  204. list. If maxsplit is nonzero, at most maxsplit splits occur,
  205. and the remainder of the string is returned as the final element
  206. of the list."""
  207. return _compile(pattern, flags).split(string, maxsplit)
  208. def findall(pattern, string, flags=0):
  209. """Return a list of all non-overlapping matches in the string.
  210. If one or more capturing groups are present in the pattern, return
  211. a list of groups; this will be a list of tuples if the pattern
  212. has more than one group.
  213. Empty matches are included in the result."""
  214. return _compile(pattern, flags).findall(string)
  215. def finditer(pattern, string, flags=0):
  216. """Return an iterator over all non-overlapping matches in the
  217. string. For each match, the iterator returns a Match object.
  218. Empty matches are included in the result."""
  219. return _compile(pattern, flags).finditer(string)
  220. def compile(pattern, flags=0):
  221. "Compile a regular expression pattern, returning a Pattern object."
  222. return _compile(pattern, flags)
  223. def purge():
  224. "Clear the regular expression caches"
  225. _cache.clear()
  226. _compile_repl.cache_clear()
  227. def template(pattern, flags=0):
  228. "Compile a template pattern, returning a Pattern object"
  229. return _compile(pattern, flags|T)
  230. # SPECIAL_CHARS
  231. # closing ')', '}' and ']'
  232. # '-' (a range in character set)
  233. # '&', '~', (extended character set operations)
  234. # '#' (comment) and WHITESPACE (ignored) in verbose mode
  235. _special_chars_map = {i: '\\' + chr(i) for i in b'()[]{}?*+-|^$\\.&~# \t\n\r\v\f'}
  236. def escape(pattern):
  237. """
  238. Escape special characters in a string.
  239. """
  240. if isinstance(pattern, str):
  241. return pattern.translate(_special_chars_map)
  242. else:
  243. pattern = str(pattern, 'latin1')
  244. return pattern.translate(_special_chars_map).encode('latin1')
  245. Pattern = type(sre_compile.compile('', 0))
  246. Match = type(sre_compile.compile('', 0).match(''))
  247. # --------------------------------------------------------------------
  248. # internals
  249. _cache = {} # ordered!
  250. _MAXCACHE = 512
  251. def _compile(pattern, flags):
  252. # internal: compile pattern
  253. if isinstance(flags, RegexFlag):
  254. flags = flags.value
  255. try:
  256. return _cache[type(pattern), pattern, flags]
  257. except KeyError:
  258. pass
  259. if isinstance(pattern, Pattern):
  260. if flags:
  261. raise ValueError(
  262. "cannot process flags argument with a compiled pattern")
  263. return pattern
  264. if not sre_compile.isstring(pattern):
  265. raise TypeError("first argument must be string or compiled pattern")
  266. p = sre_compile.compile(pattern, flags)
  267. if not (flags & DEBUG):
  268. if len(_cache) >= _MAXCACHE:
  269. # Drop the oldest item
  270. try:
  271. del _cache[next(iter(_cache))]
  272. except (StopIteration, RuntimeError, KeyError):
  273. pass
  274. _cache[type(pattern), pattern, flags] = p
  275. return p
  276. @functools.lru_cache(_MAXCACHE)
  277. def _compile_repl(repl, pattern):
  278. # internal: compile replacement pattern
  279. return sre_parse.parse_template(repl, pattern)
  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, _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. if isinstance(flags, RegexFlag):
  304. flags = flags.value
  305. self.lexicon = lexicon
  306. # combine phrases into a compound pattern
  307. p = []
  308. s = sre_parse.State()
  309. s.flags = flags
  310. for phrase, action in lexicon:
  311. gid = s.opengroup()
  312. p.append(sre_parse.SubPattern(s, [
  313. (SUBPATTERN, (gid, 0, 0, sre_parse.parse(phrase, flags))),
  314. ]))
  315. s.closegroup(gid, p[-1])
  316. p = sre_parse.SubPattern(s, [(BRANCH, (None, p))])
  317. self.scanner = sre_compile.compile(p)
  318. def scan(self, string):
  319. result = []
  320. append = result.append
  321. match = self.scanner.scanner(string).match
  322. i = 0
  323. while True:
  324. m = match()
  325. if not m:
  326. break
  327. j = m.end()
  328. if i == j:
  329. break
  330. action = self.lexicon[m.lastindex-1][1]
  331. if callable(action):
  332. self.match = m
  333. action = action(self, m.group())
  334. if action is not None:
  335. append(action)
  336. i = j
  337. return result, string[i:]