You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

701 lines
30 KiB

4 years ago
  1. #
  2. # Secret Labs' Regular Expression Engine
  3. #
  4. # Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved.
  5. #
  6. # This version of the SRE library can be redistributed under CNRI's
  7. # Python 1.6 license. For any other use, please contact Secret Labs
  8. # AB (info@pythonware.com).
  9. #
  10. # Portions of this engine have been developed in cooperation with
  11. # CNRI. Hewlett-Packard provided funding for 1.6 integration and
  12. # other compatibility work.
  13. #
  14. # 2010-01-16 mrab Python front-end re-written and extended
  15. r"""Support for regular expressions (RE).
  16. This module provides regular expression matching operations similar to those
  17. found in Perl. It supports both 8-bit and Unicode strings; both the pattern and
  18. the strings being processed can contain null bytes and characters outside the
  19. US ASCII range.
  20. Regular expressions can contain both special and ordinary characters. Most
  21. ordinary characters, like "A", "a", or "0", are the simplest regular
  22. expressions; they simply match themselves. You can concatenate ordinary
  23. characters, so last matches the string 'last'.
  24. There are a few differences between the old (legacy) behaviour and the new
  25. (enhanced) behaviour, which are indicated by VERSION0 or VERSION1.
  26. The special characters are:
  27. "." Matches any character except a newline.
  28. "^" Matches the start of the string.
  29. "$" Matches the end of the string or just before the
  30. newline at the end of the string.
  31. "*" Matches 0 or more (greedy) repetitions of the preceding
  32. RE. Greedy means that it will match as many repetitions
  33. as possible.
  34. "+" Matches 1 or more (greedy) repetitions of the preceding
  35. RE.
  36. "?" Matches 0 or 1 (greedy) of the preceding RE.
  37. *?,+?,?? Non-greedy versions of the previous three special
  38. characters.
  39. *+,++,?+ Possessive versions of the previous three special
  40. characters.
  41. {m,n} Matches from m to n repetitions of the preceding RE.
  42. {m,n}? Non-greedy version of the above.
  43. {m,n}+ Possessive version of the above.
  44. {...} Fuzzy matching constraints.
  45. "\\" Either escapes special characters or signals a special
  46. sequence.
  47. [...] Indicates a set of characters. A "^" as the first
  48. character indicates a complementing set.
  49. "|" A|B, creates an RE that will match either A or B.
  50. (...) Matches the RE inside the parentheses. The contents are
  51. captured and can be retrieved or matched later in the
  52. string.
  53. (?flags-flags) VERSION1: Sets/clears the flags for the remainder of
  54. the group or pattern; VERSION0: Sets the flags for the
  55. entire pattern.
  56. (?:...) Non-capturing version of regular parentheses.
  57. (?>...) Atomic non-capturing version of regular parentheses.
  58. (?flags-flags:...) Non-capturing version of regular parentheses with local
  59. flags.
  60. (?P<name>...) The substring matched by the group is accessible by
  61. name.
  62. (?<name>...) The substring matched by the group is accessible by
  63. name.
  64. (?P=name) Matches the text matched earlier by the group named
  65. name.
  66. (?#...) A comment; ignored.
  67. (?=...) Matches if ... matches next, but doesn't consume the
  68. string.
  69. (?!...) Matches if ... doesn't match next.
  70. (?<=...) Matches if preceded by ....
  71. (?<!...) Matches if not preceded by ....
  72. (?(id)yes|no) Matches yes pattern if group id matched, the (optional)
  73. no pattern otherwise.
  74. (?(DEFINE)...) If there's no group called "DEFINE", then ... will be
  75. ignored, but any group definitions will be available.
  76. (?|...|...) (?|A|B), creates an RE that will match either A or B,
  77. but reuses capture group numbers across the
  78. alternatives.
  79. (*FAIL) Forces matching to fail, which means immediate
  80. backtracking.
  81. (*F) Abbreviation for (*FAIL).
  82. (*PRUNE) Discards the current backtracking information. Its
  83. effect doesn't extend outside an atomic group or a
  84. lookaround.
  85. (*SKIP) Similar to (*PRUNE), except that it also sets where in
  86. the text the next attempt at matching the entire
  87. pattern will start. Its effect doesn't extend outside
  88. an atomic group or a lookaround.
  89. The fuzzy matching constraints are: "i" to permit insertions, "d" to permit
  90. deletions, "s" to permit substitutions, "e" to permit any of these. Limits are
  91. optional with "<=" and "<". If any type of error is provided then any type not
  92. provided is not permitted.
  93. A cost equation may be provided.
  94. Examples:
  95. (?:fuzzy){i<=2}
  96. (?:fuzzy){i<=1,s<=2,d<=1,1i+1s+1d<3}
  97. VERSION1: Set operators are supported, and a set can include nested sets. The
  98. set operators, in order of increasing precedence, are:
  99. || Set union ("x||y" means "x or y").
  100. ~~ (double tilde) Symmetric set difference ("x~~y" means "x or y, but not
  101. both").
  102. && Set intersection ("x&&y" means "x and y").
  103. -- (double dash) Set difference ("x--y" means "x but not y").
  104. Implicit union, ie, simple juxtaposition like in [ab], has the highest
  105. precedence.
  106. VERSION0 and VERSION1:
  107. The special sequences consist of "\\" and a character from the list below. If
  108. the ordinary character is not on the list, then the resulting RE will match the
  109. second character.
  110. \number Matches the contents of the group of the same number if
  111. number is no more than 2 digits, otherwise the character
  112. with the 3-digit octal code.
  113. \a Matches the bell character.
  114. \A Matches only at the start of the string.
  115. \b Matches the empty string, but only at the start or end of a
  116. word.
  117. \B Matches the empty string, but not at the start or end of a
  118. word.
  119. \d Matches any decimal digit; equivalent to the set [0-9] when
  120. matching a bytestring or a Unicode string with the ASCII
  121. flag, or the whole range of Unicode digits when matching a
  122. Unicode string.
  123. \D Matches any non-digit character; equivalent to [^\d].
  124. \f Matches the formfeed character.
  125. \g<name> Matches the text matched by the group named name.
  126. \G Matches the empty string, but only at the position where
  127. the search started.
  128. \K Keeps only what follows for the entire match.
  129. \L<name> Named list. The list is provided as a keyword argument.
  130. \m Matches the empty string, but only at the start of a word.
  131. \M Matches the empty string, but only at the end of a word.
  132. \n Matches the newline character.
  133. \N{name} Matches the named character.
  134. \p{name=value} Matches the character if its property has the specified
  135. value.
  136. \P{name=value} Matches the character if its property hasn't the specified
  137. value.
  138. \r Matches the carriage-return character.
  139. \s Matches any whitespace character; equivalent to
  140. [ \t\n\r\f\v].
  141. \S Matches any non-whitespace character; equivalent to [^\s].
  142. \t Matches the tab character.
  143. \uXXXX Matches the Unicode codepoint with 4-digit hex code XXXX.
  144. \UXXXXXXXX Matches the Unicode codepoint with 8-digit hex code
  145. XXXXXXXX.
  146. \v Matches the vertical tab character.
  147. \w Matches any alphanumeric character; equivalent to
  148. [a-zA-Z0-9_] when matching a bytestring or a Unicode string
  149. with the ASCII flag, or the whole range of Unicode
  150. alphanumeric characters (letters plus digits plus
  151. underscore) when matching a Unicode string. With LOCALE, it
  152. will match the set [0-9_] plus characters defined as
  153. letters for the current locale.
  154. \W Matches the complement of \w; equivalent to [^\w].
  155. \xXX Matches the character with 2-digit hex code XX.
  156. \X Matches a grapheme.
  157. \Z Matches only at the end of the string.
  158. \\ Matches a literal backslash.
  159. This module exports the following functions:
  160. match Match a regular expression pattern at the beginning of a string.
  161. fullmatch Match a regular expression pattern against all of a string.
  162. search Search a string for the presence of a pattern.
  163. sub Substitute occurrences of a pattern found in a string using a
  164. template string.
  165. subf Substitute occurrences of a pattern found in a string using a
  166. format string.
  167. subn Same as sub, but also return the number of substitutions made.
  168. subfn Same as subf, but also return the number of substitutions made.
  169. split Split a string by the occurrences of a pattern. VERSION1: will
  170. split at zero-width match; VERSION0: won't split at zero-width
  171. match.
  172. splititer Return an iterator yielding the parts of a split string.
  173. findall Find all occurrences of a pattern in a string.
  174. finditer Return an iterator yielding a match object for each match.
  175. compile Compile a pattern into a Pattern object.
  176. purge Clear the regular expression cache.
  177. escape Backslash all non-alphanumerics or special characters in a
  178. string.
  179. Most of the functions support a concurrent parameter: if True, the GIL will be
  180. released during matching, allowing other Python threads to run concurrently. If
  181. the string changes during matching, the behaviour is undefined. This parameter
  182. is not needed when working on the builtin (immutable) string classes.
  183. Some of the functions in this module take flags as optional parameters. Most of
  184. these flags can also be set within an RE:
  185. A a ASCII Make \w, \W, \b, \B, \d, and \D match the
  186. corresponding ASCII character categories. Default
  187. when matching a bytestring.
  188. B b BESTMATCH Find the best fuzzy match (default is first).
  189. D DEBUG Print the parsed pattern.
  190. E e ENHANCEMATCH Attempt to improve the fit after finding the first
  191. fuzzy match.
  192. F f FULLCASE Use full case-folding when performing
  193. case-insensitive matching in Unicode.
  194. I i IGNORECASE Perform case-insensitive matching.
  195. L L LOCALE Make \w, \W, \b, \B, \d, and \D dependent on the
  196. current locale. (One byte per character only.)
  197. M m MULTILINE "^" matches the beginning of lines (after a newline)
  198. as well as the string. "$" matches the end of lines
  199. (before a newline) as well as the end of the string.
  200. P p POSIX Perform POSIX-standard matching (leftmost longest).
  201. R r REVERSE Searches backwards.
  202. S s DOTALL "." matches any character at all, including the
  203. newline.
  204. U u UNICODE Make \w, \W, \b, \B, \d, and \D dependent on the
  205. Unicode locale. Default when matching a Unicode
  206. string.
  207. V0 V0 VERSION0 Turn on the old legacy behaviour.
  208. V1 V1 VERSION1 Turn on the new enhanced behaviour. This flag
  209. includes the FULLCASE flag.
  210. W w WORD Make \b and \B work with default Unicode word breaks
  211. and make ".", "^" and "$" work with Unicode line
  212. breaks.
  213. X x VERBOSE Ignore whitespace and comments for nicer looking REs.
  214. This module also defines an exception 'error'.
  215. """
  216. # Public symbols.
  217. __all__ = ["compile", "escape", "findall", "finditer", "fullmatch", "match",
  218. "purge", "search", "split", "splititer", "sub", "subf", "subfn", "subn",
  219. "template", "Scanner", "A", "ASCII", "B", "BESTMATCH", "D", "DEBUG", "E",
  220. "ENHANCEMATCH", "S", "DOTALL", "F", "FULLCASE", "I", "IGNORECASE", "L",
  221. "LOCALE", "M", "MULTILINE", "P", "POSIX", "R", "REVERSE", "T", "TEMPLATE",
  222. "U", "UNICODE", "V0", "VERSION0", "V1", "VERSION1", "X", "VERBOSE", "W",
  223. "WORD", "error", "Regex"]
  224. __version__ = "2.4.136"
  225. # --------------------------------------------------------------------
  226. # Public interface.
  227. def match(pattern, string, flags=0, pos=None, endpos=None, partial=False,
  228. concurrent=None, **kwargs):
  229. """Try to apply the pattern at the start of the string, returning a match
  230. object, or None if no match was found."""
  231. return _compile(pattern, flags, kwargs).match(string, pos, endpos,
  232. concurrent, partial)
  233. def fullmatch(pattern, string, flags=0, pos=None, endpos=None, partial=False,
  234. concurrent=None, **kwargs):
  235. """Try to apply the pattern against all of the string, returning a match
  236. object, or None if no match was found."""
  237. return _compile(pattern, flags, kwargs).fullmatch(string, pos, endpos,
  238. concurrent, partial)
  239. def search(pattern, string, flags=0, pos=None, endpos=None, partial=False,
  240. concurrent=None, **kwargs):
  241. """Search through string looking for a match to the pattern, returning a
  242. match object, or None if no match was found."""
  243. return _compile(pattern, flags, kwargs).search(string, pos, endpos,
  244. concurrent, partial)
  245. def sub(pattern, repl, string, count=0, flags=0, pos=None, endpos=None,
  246. concurrent=None, **kwargs):
  247. """Return the string obtained by replacing the leftmost (or rightmost with a
  248. reverse pattern) non-overlapping occurrences of the pattern in string by the
  249. replacement repl. repl can be either a string or a callable; if a string,
  250. backslash escapes in it are processed; if a callable, it's passed the match
  251. object and must return a replacement string to be used."""
  252. return _compile(pattern, flags, kwargs).sub(repl, string, count, pos,
  253. endpos, concurrent)
  254. def subf(pattern, format, string, count=0, flags=0, pos=None, endpos=None,
  255. concurrent=None, **kwargs):
  256. """Return the string obtained by replacing the leftmost (or rightmost with a
  257. reverse pattern) non-overlapping occurrences of the pattern in string by the
  258. replacement format. format can be either a string or a callable; if a string,
  259. it's treated as a format string; if a callable, it's passed the match object
  260. and must return a replacement string to be used."""
  261. return _compile(pattern, flags, kwargs).subf(format, string, count, pos,
  262. endpos, concurrent)
  263. def subn(pattern, repl, string, count=0, flags=0, pos=None, endpos=None,
  264. concurrent=None, **kwargs):
  265. """Return a 2-tuple containing (new_string, number). new_string is the string
  266. obtained by replacing the leftmost (or rightmost with a reverse pattern)
  267. non-overlapping occurrences of the pattern in the source string by the
  268. replacement repl. number is the number of substitutions that were made. repl
  269. can be either a string or a callable; if a string, backslash escapes in it
  270. are processed; if a callable, it's passed the match object and must return a
  271. replacement string to be used."""
  272. return _compile(pattern, flags, kwargs).subn(repl, string, count, pos,
  273. endpos, concurrent)
  274. def subfn(pattern, format, string, count=0, flags=0, pos=None, endpos=None,
  275. concurrent=None, **kwargs):
  276. """Return a 2-tuple containing (new_string, number). new_string is the string
  277. obtained by replacing the leftmost (or rightmost with a reverse pattern)
  278. non-overlapping occurrences of the pattern in the source string by the
  279. replacement format. number is the number of substitutions that were made. format
  280. can be either a string or a callable; if a string, it's treated as a format
  281. string; if a callable, it's passed the match object and must return a
  282. replacement string to be used."""
  283. return _compile(pattern, flags, kwargs).subfn(format, string, count, pos,
  284. endpos, concurrent)
  285. def split(pattern, string, maxsplit=0, flags=0, concurrent=None, **kwargs):
  286. """Split the source string by the occurrences of the pattern, returning a
  287. list containing the resulting substrings. If capturing parentheses are used
  288. in pattern, then the text of all groups in the pattern are also returned as
  289. part of the resulting list. If maxsplit is nonzero, at most maxsplit splits
  290. occur, and the remainder of the string is returned as the final element of
  291. the list."""
  292. return _compile(pattern, flags, kwargs).split(string, maxsplit, concurrent)
  293. def splititer(pattern, string, maxsplit=0, flags=0, concurrent=None, **kwargs):
  294. "Return an iterator yielding the parts of a split string."
  295. return _compile(pattern, flags, kwargs).splititer(string, maxsplit,
  296. concurrent)
  297. def findall(pattern, string, flags=0, pos=None, endpos=None, overlapped=False,
  298. concurrent=None, **kwargs):
  299. """Return a list of all matches in the string. The matches may be overlapped
  300. if overlapped is True. If one or more groups are present in the pattern,
  301. return a list of groups; this will be a list of tuples if the pattern has
  302. more than one group. Empty matches are included in the result."""
  303. return _compile(pattern, flags, kwargs).findall(string, pos, endpos,
  304. overlapped, concurrent)
  305. def finditer(pattern, string, flags=0, pos=None, endpos=None, overlapped=False,
  306. partial=False, concurrent=None, **kwargs):
  307. """Return an iterator over all matches in the string. The matches may be
  308. overlapped if overlapped is True. For each match, the iterator returns a
  309. match object. Empty matches are included in the result."""
  310. return _compile(pattern, flags, kwargs).finditer(string, pos, endpos,
  311. overlapped, concurrent, partial)
  312. def compile(pattern, flags=0, **kwargs):
  313. "Compile a regular expression pattern, returning a pattern object."
  314. return _compile(pattern, flags, kwargs)
  315. def purge():
  316. "Clear the regular expression cache"
  317. _cache.clear()
  318. _locale_sensitive.clear()
  319. def template(pattern, flags=0):
  320. "Compile a template pattern, returning a pattern object."
  321. return _compile(pattern, flags | TEMPLATE)
  322. def escape(pattern, special_only=True, literal_spaces=False):
  323. """Escape a string for use as a literal in a pattern. If special_only is
  324. True, escape only special characters, else escape all non-alphanumeric
  325. characters. If literal_spaces is True, don't escape spaces."""
  326. # Convert it to Unicode.
  327. if isinstance(pattern, bytes):
  328. p = pattern.decode("latin-1")
  329. else:
  330. p = pattern
  331. s = []
  332. if special_only:
  333. for c in p:
  334. if c == " " and literal_spaces:
  335. s.append(c)
  336. elif c in _METACHARS or c.isspace():
  337. s.append("\\")
  338. s.append(c)
  339. elif c == "\x00":
  340. s.append("\\000")
  341. else:
  342. s.append(c)
  343. else:
  344. for c in p:
  345. if c == " " and literal_spaces:
  346. s.append(c)
  347. elif c in _ALNUM:
  348. s.append(c)
  349. elif c == "\x00":
  350. s.append("\\000")
  351. else:
  352. s.append("\\")
  353. s.append(c)
  354. r = "".join(s)
  355. # Convert it back to bytes if necessary.
  356. if isinstance(pattern, bytes):
  357. r = r.encode("latin-1")
  358. return r
  359. # --------------------------------------------------------------------
  360. # Internals.
  361. import _regex_core
  362. import _regex
  363. from threading import RLock as _RLock
  364. from locale import getpreferredencoding as _getpreferredencoding
  365. from _regex_core import *
  366. from _regex_core import (_ALL_VERSIONS, _ALL_ENCODINGS, _FirstSetError,
  367. _UnscopedFlagSet, _check_group_features, _compile_firstset,
  368. _compile_replacement, _flatten_code, _fold_case, _get_required_string,
  369. _parse_pattern, _shrink_cache)
  370. from _regex_core import (ALNUM as _ALNUM, Info as _Info, OP as _OP, Source as
  371. _Source, Fuzzy as _Fuzzy)
  372. # Version 0 is the old behaviour, compatible with the original 're' module.
  373. # Version 1 is the new behaviour, which differs slightly.
  374. DEFAULT_VERSION = VERSION0
  375. _METACHARS = frozenset("()[]{}?*+|^$\\.-#&~")
  376. _regex_core.DEFAULT_VERSION = DEFAULT_VERSION
  377. # Caches for the patterns and replacements.
  378. _cache = {}
  379. _cache_lock = _RLock()
  380. _named_args = {}
  381. _replacement_cache = {}
  382. _locale_sensitive = {}
  383. # Maximum size of the cache.
  384. _MAXCACHE = 500
  385. _MAXREPCACHE = 500
  386. def _compile(pattern, flags=0, kwargs={}):
  387. "Compiles a regular expression to a PatternObject."
  388. # We won't bother to cache the pattern if we're debugging.
  389. debugging = (flags & DEBUG) != 0
  390. # What locale is this pattern using?
  391. locale_key = (type(pattern), pattern)
  392. if _locale_sensitive.get(locale_key, True) or (flags & LOCALE) != 0:
  393. # This pattern is, or might be, locale-sensitive.
  394. pattern_locale = _getpreferredencoding()
  395. else:
  396. # This pattern is definitely not locale-sensitive.
  397. pattern_locale = None
  398. if not debugging:
  399. try:
  400. # Do we know what keyword arguments are needed?
  401. args_key = pattern, type(pattern), flags
  402. args_needed = _named_args[args_key]
  403. # Are we being provided with its required keyword arguments?
  404. args_supplied = set()
  405. if args_needed:
  406. for k, v in args_needed:
  407. try:
  408. args_supplied.add((k, frozenset(kwargs[k])))
  409. except KeyError:
  410. raise error("missing named list: {!r}".format(k))
  411. args_supplied = frozenset(args_supplied)
  412. # Have we already seen this regular expression and named list?
  413. pattern_key = (pattern, type(pattern), flags, args_supplied,
  414. DEFAULT_VERSION, pattern_locale)
  415. return _cache[pattern_key]
  416. except KeyError:
  417. # It's a new pattern, or new named list for a known pattern.
  418. pass
  419. # Guess the encoding from the class of the pattern string.
  420. if isinstance(pattern, str):
  421. guess_encoding = UNICODE
  422. elif isinstance(pattern, bytes):
  423. guess_encoding = ASCII
  424. elif isinstance(pattern, _pattern_type):
  425. if flags:
  426. raise ValueError("cannot process flags argument with a compiled pattern")
  427. return pattern
  428. else:
  429. raise TypeError("first argument must be a string or compiled pattern")
  430. # Set the default version in the core code in case it has been changed.
  431. _regex_core.DEFAULT_VERSION = DEFAULT_VERSION
  432. global_flags = flags
  433. while True:
  434. caught_exception = None
  435. try:
  436. source = _Source(pattern)
  437. info = _Info(global_flags, source.char_type, kwargs)
  438. info.guess_encoding = guess_encoding
  439. source.ignore_space = bool(info.flags & VERBOSE)
  440. parsed = _parse_pattern(source, info)
  441. break
  442. except _UnscopedFlagSet:
  443. # Remember the global flags for the next attempt.
  444. global_flags = info.global_flags
  445. except error as e:
  446. caught_exception = e
  447. if caught_exception:
  448. raise error(caught_exception.msg, caught_exception.pattern,
  449. caught_exception.pos)
  450. if not source.at_end():
  451. raise error("unbalanced parenthesis", pattern, source.pos)
  452. # Check the global flags for conflicts.
  453. version = (info.flags & _ALL_VERSIONS) or DEFAULT_VERSION
  454. if version not in (0, VERSION0, VERSION1):
  455. raise ValueError("VERSION0 and VERSION1 flags are mutually incompatible")
  456. if (info.flags & _ALL_ENCODINGS) not in (0, ASCII, LOCALE, UNICODE):
  457. raise ValueError("ASCII, LOCALE and UNICODE flags are mutually incompatible")
  458. if isinstance(pattern, bytes) and (info.flags & UNICODE):
  459. raise ValueError("cannot use UNICODE flag with a bytes pattern")
  460. if not (info.flags & _ALL_ENCODINGS):
  461. if isinstance(pattern, str):
  462. info.flags |= UNICODE
  463. else:
  464. info.flags |= ASCII
  465. reverse = bool(info.flags & REVERSE)
  466. fuzzy = isinstance(parsed, _Fuzzy)
  467. # Remember whether this pattern as an inline locale flag.
  468. _locale_sensitive[locale_key] = info.inline_locale
  469. # Fix the group references.
  470. caught_exception = None
  471. try:
  472. parsed.fix_groups(pattern, reverse, False)
  473. except error as e:
  474. caught_exception = e
  475. if caught_exception:
  476. raise error(caught_exception.msg, caught_exception.pattern,
  477. caught_exception.pos)
  478. # Should we print the parsed pattern?
  479. if flags & DEBUG:
  480. parsed.dump(indent=0, reverse=reverse)
  481. # Optimise the parsed pattern.
  482. parsed = parsed.optimise(info, reverse)
  483. parsed = parsed.pack_characters(info)
  484. # Get the required string.
  485. req_offset, req_chars, req_flags = _get_required_string(parsed, info.flags)
  486. # Build the named lists.
  487. named_lists = {}
  488. named_list_indexes = [None] * len(info.named_lists_used)
  489. args_needed = set()
  490. for key, index in info.named_lists_used.items():
  491. name, case_flags = key
  492. values = frozenset(kwargs[name])
  493. if case_flags:
  494. items = frozenset(_fold_case(info, v) for v in values)
  495. else:
  496. items = values
  497. named_lists[name] = values
  498. named_list_indexes[index] = items
  499. args_needed.add((name, values))
  500. # Check the features of the groups.
  501. _check_group_features(info, parsed)
  502. # Compile the parsed pattern. The result is a list of tuples.
  503. code = parsed.compile(reverse)
  504. # Is there a group call to the pattern as a whole?
  505. key = (0, reverse, fuzzy)
  506. ref = info.call_refs.get(key)
  507. if ref is not None:
  508. code = [(_OP.CALL_REF, ref)] + code + [(_OP.END, )]
  509. # Add the final 'success' opcode.
  510. code += [(_OP.SUCCESS, )]
  511. # Compile the additional copies of the groups that we need.
  512. for group, rev, fuz in info.additional_groups:
  513. code += group.compile(rev, fuz)
  514. # Flatten the code into a list of ints.
  515. code = _flatten_code(code)
  516. if not parsed.has_simple_start():
  517. # Get the first set, if possible.
  518. try:
  519. fs_code = _compile_firstset(info, parsed.get_firstset(reverse))
  520. fs_code = _flatten_code(fs_code)
  521. code = fs_code + code
  522. except _FirstSetError:
  523. pass
  524. # The named capture groups.
  525. index_group = dict((v, n) for n, v in info.group_index.items())
  526. # Create the PatternObject.
  527. #
  528. # Local flags like IGNORECASE affect the code generation, but aren't needed
  529. # by the PatternObject itself. Conversely, global flags like LOCALE _don't_
  530. # affect the code generation but _are_ needed by the PatternObject.
  531. compiled_pattern = _regex.compile(pattern, info.flags | version, code,
  532. info.group_index, index_group, named_lists, named_list_indexes,
  533. req_offset, req_chars, req_flags, info.group_count)
  534. # Do we need to reduce the size of the cache?
  535. if len(_cache) >= _MAXCACHE:
  536. with _cache_lock:
  537. _shrink_cache(_cache, _named_args, _locale_sensitive, _MAXCACHE)
  538. if not debugging:
  539. if (info.flags & LOCALE) == 0:
  540. pattern_locale = None
  541. args_needed = frozenset(args_needed)
  542. # Store this regular expression and named list.
  543. pattern_key = (pattern, type(pattern), flags, args_needed,
  544. DEFAULT_VERSION, pattern_locale)
  545. _cache[pattern_key] = compiled_pattern
  546. # Store what keyword arguments are needed.
  547. _named_args[args_key] = args_needed
  548. return compiled_pattern
  549. def _compile_replacement_helper(pattern, template):
  550. "Compiles a replacement template."
  551. # This function is called by the _regex module.
  552. # Have we seen this before?
  553. key = pattern.pattern, pattern.flags, template
  554. compiled = _replacement_cache.get(key)
  555. if compiled is not None:
  556. return compiled
  557. if len(_replacement_cache) >= _MAXREPCACHE:
  558. _replacement_cache.clear()
  559. is_unicode = isinstance(template, str)
  560. source = _Source(template)
  561. if is_unicode:
  562. def make_string(char_codes):
  563. return "".join(chr(c) for c in char_codes)
  564. else:
  565. def make_string(char_codes):
  566. return bytes(char_codes)
  567. compiled = []
  568. literal = []
  569. while True:
  570. ch = source.get()
  571. if not ch:
  572. break
  573. if ch == "\\":
  574. # '_compile_replacement' will return either an int group reference
  575. # or a string literal. It returns items (plural) in order to handle
  576. # a 2-character literal (an invalid escape sequence).
  577. is_group, items = _compile_replacement(source, pattern, is_unicode)
  578. if is_group:
  579. # It's a group, so first flush the literal.
  580. if literal:
  581. compiled.append(make_string(literal))
  582. literal = []
  583. compiled.extend(items)
  584. else:
  585. literal.extend(items)
  586. else:
  587. literal.append(ord(ch))
  588. # Flush the literal.
  589. if literal:
  590. compiled.append(make_string(literal))
  591. _replacement_cache[key] = compiled
  592. return compiled
  593. # We define _pattern_type here after all the support objects have been defined.
  594. _pattern_type = type(_compile("", 0, {}))
  595. # We'll define an alias for the 'compile' function so that the repr of a
  596. # pattern object is eval-able.
  597. Regex = compile
  598. # Register myself for pickling.
  599. import copyreg as _copy_reg
  600. def _pickle(pattern):
  601. return _regex.compile, pattern._pickled_data
  602. _copy_reg.pickle(_pattern_type, _pickle)