regex.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  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. \h Matches horizontal whitespace.
  129. \K Keeps only what follows for the entire match.
  130. \L<name> Named list. The list is provided as a keyword argument.
  131. \m Matches the empty string, but only at the start of a word.
  132. \M Matches the empty string, but only at the end of a word.
  133. \n Matches the newline character.
  134. \N{name} Matches the named character.
  135. \p{name=value} Matches the character if its property has the specified
  136. value.
  137. \P{name=value} Matches the character if its property hasn't the specified
  138. value.
  139. \r Matches the carriage-return character.
  140. \s Matches any whitespace character; equivalent to
  141. [ \t\n\r\f\v].
  142. \S Matches any non-whitespace character; equivalent to [^\s].
  143. \t Matches the tab character.
  144. \uXXXX Matches the Unicode codepoint with 4-digit hex code XXXX.
  145. \UXXXXXXXX Matches the Unicode codepoint with 8-digit hex code
  146. XXXXXXXX.
  147. \v Matches the vertical tab character.
  148. \w Matches any alphanumeric character; equivalent to
  149. [a-zA-Z0-9_] when matching a bytestring or a Unicode string
  150. with the ASCII flag, or the whole range of Unicode
  151. alphanumeric characters (letters plus digits plus
  152. underscore) when matching a Unicode string. With LOCALE, it
  153. will match the set [0-9_] plus characters defined as
  154. letters for the current locale.
  155. \W Matches the complement of \w; equivalent to [^\w].
  156. \xXX Matches the character with 2-digit hex code XX.
  157. \X Matches a grapheme.
  158. \Z Matches only at the end of the string.
  159. \\ Matches a literal backslash.
  160. This module exports the following functions:
  161. match Match a regular expression pattern at the beginning of a string.
  162. fullmatch Match a regular expression pattern against all of a string.
  163. search Search a string for the presence of a pattern.
  164. sub Substitute occurrences of a pattern found in a string using a
  165. template string.
  166. subf Substitute occurrences of a pattern found in a string using a
  167. format string.
  168. subn Same as sub, but also return the number of substitutions made.
  169. subfn Same as subf, but also return the number of substitutions made.
  170. split Split a string by the occurrences of a pattern. VERSION1: will
  171. split at zero-width match; VERSION0: won't split at zero-width
  172. match.
  173. splititer Return an iterator yielding the parts of a split string.
  174. findall Find all occurrences of a pattern in a string.
  175. finditer Return an iterator yielding a match object for each match.
  176. compile Compile a pattern into a Pattern object.
  177. purge Clear the regular expression cache.
  178. escape Backslash all non-alphanumerics or special characters in a
  179. string.
  180. Most of the functions support a concurrent parameter: if True, the GIL will be
  181. released during matching, allowing other Python threads to run concurrently. If
  182. the string changes during matching, the behaviour is undefined. This parameter
  183. is not needed when working on the builtin (immutable) string classes.
  184. Some of the functions in this module take flags as optional parameters. Most of
  185. these flags can also be set within an RE:
  186. A a ASCII Make \w, \W, \b, \B, \d, and \D match the
  187. corresponding ASCII character categories. Default
  188. when matching a bytestring.
  189. B b BESTMATCH Find the best fuzzy match (default is first).
  190. D DEBUG Print the parsed pattern.
  191. E e ENHANCEMATCH Attempt to improve the fit after finding the first
  192. fuzzy match.
  193. F f FULLCASE Use full case-folding when performing
  194. case-insensitive matching in Unicode.
  195. I i IGNORECASE Perform case-insensitive matching.
  196. L L LOCALE Make \w, \W, \b, \B, \d, and \D dependent on the
  197. current locale. (One byte per character only.)
  198. M m MULTILINE "^" matches the beginning of lines (after a newline)
  199. as well as the string. "$" matches the end of lines
  200. (before a newline) as well as the end of the string.
  201. P p POSIX Perform POSIX-standard matching (leftmost longest).
  202. R r REVERSE Searches backwards.
  203. S s DOTALL "." matches any character at all, including the
  204. newline.
  205. U u UNICODE Make \w, \W, \b, \B, \d, and \D dependent on the
  206. Unicode locale. Default when matching a Unicode
  207. string.
  208. V0 V0 VERSION0 Turn on the old legacy behaviour.
  209. V1 V1 VERSION1 Turn on the new enhanced behaviour. This flag
  210. includes the FULLCASE flag.
  211. W w WORD Make \b and \B work with default Unicode word breaks
  212. and make ".", "^" and "$" work with Unicode line
  213. breaks.
  214. X x VERBOSE Ignore whitespace and comments for nicer looking REs.
  215. This module also defines an exception 'error'.
  216. """
  217. # Public symbols.
  218. __all__ = ["compile", "DEFAULT_VERSION", "escape", "findall", "finditer",
  219. "fullmatch", "match", "purge", "search", "split", "splititer", "sub", "subf",
  220. "subfn", "subn", "template", "Scanner", "A", "ASCII", "B", "BESTMATCH", "D",
  221. "DEBUG", "E", "ENHANCEMATCH", "S", "DOTALL", "F", "FULLCASE", "I",
  222. "IGNORECASE", "L", "LOCALE", "M", "MULTILINE", "P", "POSIX", "R", "REVERSE",
  223. "T", "TEMPLATE", "U", "UNICODE", "V0", "VERSION0", "V1", "VERSION1", "X",
  224. "VERBOSE", "W", "WORD", "error", "Regex", "__version__", "__doc__"]
  225. __version__ = "2.5.83"
  226. # --------------------------------------------------------------------
  227. # Public interface.
  228. def match(pattern, string, flags=0, pos=None, endpos=None, partial=False,
  229. concurrent=None, timeout=None, ignore_unused=False, **kwargs):
  230. """Try to apply the pattern at the start of the string, returning a match
  231. object, or None if no match was found."""
  232. return _compile(pattern, flags, ignore_unused, kwargs).match(string, pos,
  233. endpos, concurrent, partial, timeout)
  234. def fullmatch(pattern, string, flags=0, pos=None, endpos=None, partial=False,
  235. concurrent=None, timeout=None, ignore_unused=False, **kwargs):
  236. """Try to apply the pattern against all of the string, returning a match
  237. object, or None if no match was found."""
  238. return _compile(pattern, flags, ignore_unused, kwargs).fullmatch(string,
  239. pos, endpos, concurrent, partial, timeout)
  240. def search(pattern, string, flags=0, pos=None, endpos=None, partial=False,
  241. concurrent=None, timeout=None, ignore_unused=False, **kwargs):
  242. """Search through string looking for a match to the pattern, returning a
  243. match object, or None if no match was found."""
  244. return _compile(pattern, flags, ignore_unused, kwargs).search(string, pos,
  245. endpos, concurrent, partial, timeout)
  246. def sub(pattern, repl, string, count=0, flags=0, pos=None, endpos=None,
  247. concurrent=None, timeout=None, ignore_unused=False, **kwargs):
  248. """Return the string obtained by replacing the leftmost (or rightmost with a
  249. reverse pattern) non-overlapping occurrences of the pattern in string by the
  250. replacement repl. repl can be either a string or a callable; if a string,
  251. backslash escapes in it are processed; if a callable, it's passed the match
  252. object and must return a replacement string to be used."""
  253. return _compile(pattern, flags, ignore_unused, kwargs).sub(repl, string,
  254. count, pos, endpos, concurrent, timeout)
  255. def subf(pattern, format, string, count=0, flags=0, pos=None, endpos=None,
  256. concurrent=None, timeout=None, ignore_unused=False, **kwargs):
  257. """Return the string obtained by replacing the leftmost (or rightmost with a
  258. reverse pattern) non-overlapping occurrences of the pattern in string by the
  259. replacement format. format can be either a string or a callable; if a string,
  260. it's treated as a format string; if a callable, it's passed the match object
  261. and must return a replacement string to be used."""
  262. return _compile(pattern, flags, ignore_unused, kwargs).subf(format, string,
  263. count, pos, endpos, concurrent, timeout)
  264. def subn(pattern, repl, string, count=0, flags=0, pos=None, endpos=None,
  265. concurrent=None, timeout=None, ignore_unused=False, **kwargs):
  266. """Return a 2-tuple containing (new_string, number). new_string is the string
  267. obtained by replacing the leftmost (or rightmost with a reverse pattern)
  268. non-overlapping occurrences of the pattern in the source string by the
  269. replacement repl. number is the number of substitutions that were made. repl
  270. can be either a string or a callable; if a string, backslash escapes in it
  271. are processed; if a callable, it's passed the match object and must return a
  272. replacement string to be used."""
  273. return _compile(pattern, flags, ignore_unused, kwargs).subn(repl, string,
  274. count, pos, endpos, concurrent, timeout)
  275. def subfn(pattern, format, string, count=0, flags=0, pos=None, endpos=None,
  276. concurrent=None, timeout=None, ignore_unused=False, **kwargs):
  277. """Return a 2-tuple containing (new_string, number). new_string is the string
  278. obtained by replacing the leftmost (or rightmost with a reverse pattern)
  279. non-overlapping occurrences of the pattern in the source string by the
  280. replacement format. number is the number of substitutions that were made. format
  281. can be either a string or a callable; if a string, it's treated as a format
  282. string; if a callable, it's passed the match object and must return a
  283. replacement string to be used."""
  284. return _compile(pattern, flags, ignore_unused, kwargs).subfn(format, string,
  285. count, pos, endpos, concurrent, timeout)
  286. def split(pattern, string, maxsplit=0, flags=0, concurrent=None, timeout=None,
  287. ignore_unused=False, **kwargs):
  288. """Split the source string by the occurrences of the pattern, returning a
  289. list containing the resulting substrings. If capturing parentheses are used
  290. in pattern, then the text of all groups in the pattern are also returned as
  291. part of the resulting list. If maxsplit is nonzero, at most maxsplit splits
  292. occur, and the remainder of the string is returned as the final element of
  293. the list."""
  294. return _compile(pattern, flags, ignore_unused, kwargs).split(string,
  295. maxsplit, concurrent, timeout)
  296. def splititer(pattern, string, maxsplit=0, flags=0, concurrent=None, timeout=None,
  297. ignore_unused=False, **kwargs):
  298. "Return an iterator yielding the parts of a split string."
  299. return _compile(pattern, flags, ignore_unused, kwargs).splititer(string,
  300. maxsplit, concurrent, timeout)
  301. def findall(pattern, string, flags=0, pos=None, endpos=None, overlapped=False,
  302. concurrent=None, timeout=None, ignore_unused=False, **kwargs):
  303. """Return a list of all matches in the string. The matches may be overlapped
  304. if overlapped is True. If one or more groups are present in the pattern,
  305. return a list of groups; this will be a list of tuples if the pattern has
  306. more than one group. Empty matches are included in the result."""
  307. return _compile(pattern, flags, ignore_unused, kwargs).findall(string, pos,
  308. endpos, overlapped, concurrent, timeout)
  309. def finditer(pattern, string, flags=0, pos=None, endpos=None, overlapped=False,
  310. partial=False, concurrent=None, timeout=None, ignore_unused=False, **kwargs):
  311. """Return an iterator over all matches in the string. The matches may be
  312. overlapped if overlapped is True. For each match, the iterator returns a
  313. match object. Empty matches are included in the result."""
  314. return _compile(pattern, flags, ignore_unused, kwargs).finditer(string, pos,
  315. endpos, overlapped, concurrent, partial, timeout)
  316. def compile(pattern, flags=0, ignore_unused=False, **kwargs):
  317. "Compile a regular expression pattern, returning a pattern object."
  318. return _compile(pattern, flags, ignore_unused, kwargs)
  319. def purge():
  320. "Clear the regular expression cache"
  321. _cache.clear()
  322. _locale_sensitive.clear()
  323. def template(pattern, flags=0):
  324. "Compile a template pattern, returning a pattern object."
  325. return _compile(pattern, flags | TEMPLATE, False, {})
  326. def escape(pattern, special_only=True, literal_spaces=False):
  327. """Escape a string for use as a literal in a pattern. If special_only is
  328. True, escape only special characters, else escape all non-alphanumeric
  329. characters. If literal_spaces is True, don't escape spaces."""
  330. # Convert it to Unicode.
  331. if isinstance(pattern, bytes):
  332. p = pattern.decode("latin-1")
  333. else:
  334. p = pattern
  335. s = []
  336. if special_only:
  337. for c in p:
  338. if c == " " and literal_spaces:
  339. s.append(c)
  340. elif c in _METACHARS or c.isspace():
  341. s.append("\\")
  342. s.append(c)
  343. elif c == "\x00":
  344. s.append("\\000")
  345. else:
  346. s.append(c)
  347. else:
  348. for c in p:
  349. if c == " " and literal_spaces:
  350. s.append(c)
  351. elif c in _ALNUM:
  352. s.append(c)
  353. elif c == "\x00":
  354. s.append("\\000")
  355. else:
  356. s.append("\\")
  357. s.append(c)
  358. r = "".join(s)
  359. # Convert it back to bytes if necessary.
  360. if isinstance(pattern, bytes):
  361. r = r.encode("latin-1")
  362. return r
  363. # --------------------------------------------------------------------
  364. # Internals.
  365. import regex._regex_core as _regex_core
  366. import regex._regex as _regex
  367. from threading import RLock as _RLock
  368. from locale import getpreferredencoding as _getpreferredencoding
  369. from regex._regex_core import *
  370. from regex._regex_core import (_ALL_VERSIONS, _ALL_ENCODINGS, _FirstSetError,
  371. _UnscopedFlagSet, _check_group_features, _compile_firstset,
  372. _compile_replacement, _flatten_code, _fold_case, _get_required_string,
  373. _parse_pattern, _shrink_cache)
  374. from regex._regex_core import (ALNUM as _ALNUM, Info as _Info, OP as _OP, Source
  375. as _Source, Fuzzy as _Fuzzy)
  376. # Version 0 is the old behaviour, compatible with the original 're' module.
  377. # Version 1 is the new behaviour, which differs slightly.
  378. DEFAULT_VERSION = VERSION0
  379. _METACHARS = frozenset("()[]{}?*+|^$\\.-#&~")
  380. _regex_core.DEFAULT_VERSION = DEFAULT_VERSION
  381. # Caches for the patterns and replacements.
  382. _cache = {}
  383. _cache_lock = _RLock()
  384. _named_args = {}
  385. _replacement_cache = {}
  386. _locale_sensitive = {}
  387. # Maximum size of the cache.
  388. _MAXCACHE = 500
  389. _MAXREPCACHE = 500
  390. def _compile(pattern, flags, ignore_unused, kwargs):
  391. "Compiles a regular expression to a PatternObject."
  392. global DEFAULT_VERSION
  393. try:
  394. from regex import DEFAULT_VERSION
  395. except ImportError:
  396. pass
  397. # We won't bother to cache the pattern if we're debugging.
  398. debugging = (flags & DEBUG) != 0
  399. # What locale is this pattern using?
  400. locale_key = (type(pattern), pattern)
  401. if _locale_sensitive.get(locale_key, True) or (flags & LOCALE) != 0:
  402. # This pattern is, or might be, locale-sensitive.
  403. pattern_locale = _getpreferredencoding()
  404. else:
  405. # This pattern is definitely not locale-sensitive.
  406. pattern_locale = None
  407. if not debugging:
  408. try:
  409. # Do we know what keyword arguments are needed?
  410. args_key = pattern, type(pattern), flags
  411. args_needed = _named_args[args_key]
  412. # Are we being provided with its required keyword arguments?
  413. args_supplied = set()
  414. if args_needed:
  415. for k, v in args_needed:
  416. try:
  417. args_supplied.add((k, frozenset(kwargs[k])))
  418. except KeyError:
  419. raise error("missing named list: {!r}".format(k))
  420. args_supplied = frozenset(args_supplied)
  421. # Have we already seen this regular expression and named list?
  422. pattern_key = (pattern, type(pattern), flags, args_supplied,
  423. DEFAULT_VERSION, pattern_locale)
  424. return _cache[pattern_key]
  425. except KeyError:
  426. # It's a new pattern, or new named list for a known pattern.
  427. pass
  428. # Guess the encoding from the class of the pattern string.
  429. if isinstance(pattern, str):
  430. guess_encoding = UNICODE
  431. elif isinstance(pattern, bytes):
  432. guess_encoding = ASCII
  433. elif isinstance(pattern, Pattern):
  434. if flags:
  435. raise ValueError("cannot process flags argument with a compiled pattern")
  436. return pattern
  437. else:
  438. raise TypeError("first argument must be a string or compiled pattern")
  439. # Set the default version in the core code in case it has been changed.
  440. _regex_core.DEFAULT_VERSION = DEFAULT_VERSION
  441. global_flags = flags
  442. while True:
  443. caught_exception = None
  444. try:
  445. source = _Source(pattern)
  446. info = _Info(global_flags, source.char_type, kwargs)
  447. info.guess_encoding = guess_encoding
  448. source.ignore_space = bool(info.flags & VERBOSE)
  449. parsed = _parse_pattern(source, info)
  450. break
  451. except _UnscopedFlagSet:
  452. # Remember the global flags for the next attempt.
  453. global_flags = info.global_flags
  454. except error as e:
  455. caught_exception = e
  456. if caught_exception:
  457. raise error(caught_exception.msg, caught_exception.pattern,
  458. caught_exception.pos)
  459. if not source.at_end():
  460. raise error("unbalanced parenthesis", pattern, source.pos)
  461. # Check the global flags for conflicts.
  462. version = (info.flags & _ALL_VERSIONS) or DEFAULT_VERSION
  463. if version not in (0, VERSION0, VERSION1):
  464. raise ValueError("VERSION0 and VERSION1 flags are mutually incompatible")
  465. if (info.flags & _ALL_ENCODINGS) not in (0, ASCII, LOCALE, UNICODE):
  466. raise ValueError("ASCII, LOCALE and UNICODE flags are mutually incompatible")
  467. if isinstance(pattern, bytes) and (info.flags & UNICODE):
  468. raise ValueError("cannot use UNICODE flag with a bytes pattern")
  469. if not (info.flags & _ALL_ENCODINGS):
  470. if isinstance(pattern, str):
  471. info.flags |= UNICODE
  472. else:
  473. info.flags |= ASCII
  474. reverse = bool(info.flags & REVERSE)
  475. fuzzy = isinstance(parsed, _Fuzzy)
  476. # Remember whether this pattern as an inline locale flag.
  477. _locale_sensitive[locale_key] = info.inline_locale
  478. # Fix the group references.
  479. caught_exception = None
  480. try:
  481. parsed.fix_groups(pattern, reverse, False)
  482. except error as e:
  483. caught_exception = e
  484. if caught_exception:
  485. raise error(caught_exception.msg, caught_exception.pattern,
  486. caught_exception.pos)
  487. # Should we print the parsed pattern?
  488. if flags & DEBUG:
  489. parsed.dump(indent=0, reverse=reverse)
  490. # Optimise the parsed pattern.
  491. parsed = parsed.optimise(info, reverse)
  492. parsed = parsed.pack_characters(info)
  493. # Get the required string.
  494. req_offset, req_chars, req_flags = _get_required_string(parsed, info.flags)
  495. # Build the named lists.
  496. named_lists = {}
  497. named_list_indexes = [None] * len(info.named_lists_used)
  498. args_needed = set()
  499. for key, index in info.named_lists_used.items():
  500. name, case_flags = key
  501. values = frozenset(kwargs[name])
  502. if case_flags:
  503. items = frozenset(_fold_case(info, v) for v in values)
  504. else:
  505. items = values
  506. named_lists[name] = values
  507. named_list_indexes[index] = items
  508. args_needed.add((name, values))
  509. # Any unused keyword arguments, possibly resulting from a typo?
  510. unused_kwargs = set(kwargs) - set(named_lists)
  511. if unused_kwargs and not ignore_unused:
  512. any_one = next(iter(unused_kwargs))
  513. raise ValueError('unused keyword argument {!a}'.format(any_one))
  514. # Check the features of the groups.
  515. _check_group_features(info, parsed)
  516. # Compile the parsed pattern. The result is a list of tuples.
  517. code = parsed.compile(reverse)
  518. # Is there a group call to the pattern as a whole?
  519. key = (0, reverse, fuzzy)
  520. ref = info.call_refs.get(key)
  521. if ref is not None:
  522. code = [(_OP.CALL_REF, ref)] + code + [(_OP.END, )]
  523. # Add the final 'success' opcode.
  524. code += [(_OP.SUCCESS, )]
  525. # Compile the additional copies of the groups that we need.
  526. for group, rev, fuz in info.additional_groups:
  527. code += group.compile(rev, fuz)
  528. # Flatten the code into a list of ints.
  529. code = _flatten_code(code)
  530. if not parsed.has_simple_start():
  531. # Get the first set, if possible.
  532. try:
  533. fs_code = _compile_firstset(info, parsed.get_firstset(reverse))
  534. fs_code = _flatten_code(fs_code)
  535. code = fs_code + code
  536. except _FirstSetError:
  537. pass
  538. # The named capture groups.
  539. index_group = dict((v, n) for n, v in info.group_index.items())
  540. # Create the PatternObject.
  541. #
  542. # Local flags like IGNORECASE affect the code generation, but aren't needed
  543. # by the PatternObject itself. Conversely, global flags like LOCALE _don't_
  544. # affect the code generation but _are_ needed by the PatternObject.
  545. compiled_pattern = _regex.compile(pattern, info.flags | version, code,
  546. info.group_index, index_group, named_lists, named_list_indexes,
  547. req_offset, req_chars, req_flags, info.group_count)
  548. # Do we need to reduce the size of the cache?
  549. if len(_cache) >= _MAXCACHE:
  550. with _cache_lock:
  551. _shrink_cache(_cache, _named_args, _locale_sensitive, _MAXCACHE)
  552. if not debugging:
  553. if (info.flags & LOCALE) == 0:
  554. pattern_locale = None
  555. args_needed = frozenset(args_needed)
  556. # Store this regular expression and named list.
  557. pattern_key = (pattern, type(pattern), flags, args_needed,
  558. DEFAULT_VERSION, pattern_locale)
  559. _cache[pattern_key] = compiled_pattern
  560. # Store what keyword arguments are needed.
  561. _named_args[args_key] = args_needed
  562. return compiled_pattern
  563. def _compile_replacement_helper(pattern, template):
  564. "Compiles a replacement template."
  565. # This function is called by the _regex module.
  566. # Have we seen this before?
  567. key = pattern.pattern, pattern.flags, template
  568. compiled = _replacement_cache.get(key)
  569. if compiled is not None:
  570. return compiled
  571. if len(_replacement_cache) >= _MAXREPCACHE:
  572. _replacement_cache.clear()
  573. is_unicode = isinstance(template, str)
  574. source = _Source(template)
  575. if is_unicode:
  576. def make_string(char_codes):
  577. return "".join(chr(c) for c in char_codes)
  578. else:
  579. def make_string(char_codes):
  580. return bytes(char_codes)
  581. compiled = []
  582. literal = []
  583. while True:
  584. ch = source.get()
  585. if not ch:
  586. break
  587. if ch == "\\":
  588. # '_compile_replacement' will return either an int group reference
  589. # or a string literal. It returns items (plural) in order to handle
  590. # a 2-character literal (an invalid escape sequence).
  591. is_group, items = _compile_replacement(source, pattern, is_unicode)
  592. if is_group:
  593. # It's a group, so first flush the literal.
  594. if literal:
  595. compiled.append(make_string(literal))
  596. literal = []
  597. compiled.extend(items)
  598. else:
  599. literal.extend(items)
  600. else:
  601. literal.append(ord(ch))
  602. # Flush the literal.
  603. if literal:
  604. compiled.append(make_string(literal))
  605. _replacement_cache[key] = compiled
  606. return compiled
  607. # We define Pattern here after all the support objects have been defined.
  608. Pattern = type(_compile('', 0, False, {}))
  609. Match = type(_compile('', 0, False, {}).match(''))
  610. # We'll define an alias for the 'compile' function so that the repr of a
  611. # pattern object is eval-able.
  612. Regex = compile
  613. # Register myself for pickling.
  614. import copyreg as _copy_reg
  615. def _pickle(pattern):
  616. return _regex.compile, pattern._pickled_data
  617. _copy_reg.pickle(Pattern, _pickle)