_main.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  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__ = ["cache_all", "compile", "DEFAULT_VERSION", "escape", "findall",
  219. "finditer", "fullmatch", "match", "purge", "search", "split", "splititer",
  220. "sub", "subf", "subfn", "subn", "template", "Scanner", "A", "ASCII", "B",
  221. "BESTMATCH", "D", "DEBUG", "E", "ENHANCEMATCH", "S", "DOTALL", "F",
  222. "FULLCASE", "I", "IGNORECASE", "L", "LOCALE", "M", "MULTILINE", "P", "POSIX",
  223. "R", "REVERSE", "T", "TEMPLATE", "U", "UNICODE", "V0", "VERSION0", "V1",
  224. "VERSION1", "X", "VERBOSE", "W", "WORD", "error", "Regex", "__version__",
  225. "__doc__", "RegexFlag"]
  226. __version__ = "2025.11.3"
  227. # --------------------------------------------------------------------
  228. # Public interface.
  229. def match(pattern, string, flags=0, pos=None, endpos=None, partial=False,
  230. concurrent=None, timeout=None, ignore_unused=False, **kwargs):
  231. """Try to apply the pattern at the start of the string, returning a match
  232. object, or None if no match was found."""
  233. pat = _compile(pattern, flags, ignore_unused, kwargs, True)
  234. return pat.match(string, pos, endpos, concurrent, partial, timeout)
  235. def fullmatch(pattern, string, flags=0, pos=None, endpos=None, partial=False,
  236. concurrent=None, timeout=None, ignore_unused=False, **kwargs):
  237. """Try to apply the pattern against all of the string, returning a match
  238. object, or None if no match was found."""
  239. pat = _compile(pattern, flags, ignore_unused, kwargs, True)
  240. return pat.fullmatch(string, pos, endpos, concurrent, partial, timeout)
  241. def search(pattern, string, flags=0, pos=None, endpos=None, partial=False,
  242. concurrent=None, timeout=None, ignore_unused=False, **kwargs):
  243. """Search through string looking for a match to the pattern, returning a
  244. match object, or None if no match was found."""
  245. pat = _compile(pattern, flags, ignore_unused, kwargs, True)
  246. return pat.search(string, pos, endpos, concurrent, partial, timeout)
  247. def sub(pattern, repl, string, count=0, flags=0, pos=None, endpos=None,
  248. concurrent=None, timeout=None, ignore_unused=False, **kwargs):
  249. """Return the string obtained by replacing the leftmost (or rightmost with a
  250. reverse pattern) non-overlapping occurrences of the pattern in string by the
  251. replacement repl. repl can be either a string or a callable; if a string,
  252. backslash escapes in it are processed; if a callable, it's passed the match
  253. object and must return a replacement string to be used."""
  254. pat = _compile(pattern, flags, ignore_unused, kwargs, True)
  255. return pat.sub(repl, string, count, pos, endpos, concurrent, timeout)
  256. def subf(pattern, format, string, count=0, flags=0, pos=None, endpos=None,
  257. concurrent=None, timeout=None, ignore_unused=False, **kwargs):
  258. """Return the string obtained by replacing the leftmost (or rightmost with a
  259. reverse pattern) non-overlapping occurrences of the pattern in string by the
  260. replacement format. format can be either a string or a callable; if a string,
  261. it's treated as a format string; if a callable, it's passed the match object
  262. and must return a replacement string to be used."""
  263. pat = _compile(pattern, flags, ignore_unused, kwargs, True)
  264. return pat.subf(format, string, count, pos, endpos, concurrent, timeout)
  265. def subn(pattern, repl, string, count=0, flags=0, pos=None, endpos=None,
  266. concurrent=None, timeout=None, ignore_unused=False, **kwargs):
  267. """Return a 2-tuple containing (new_string, number). new_string is the string
  268. obtained by replacing the leftmost (or rightmost with a reverse pattern)
  269. non-overlapping occurrences of the pattern in the source string by the
  270. replacement repl. number is the number of substitutions that were made. repl
  271. can be either a string or a callable; if a string, backslash escapes in it
  272. are processed; if a callable, it's passed the match object and must return a
  273. replacement string to be used."""
  274. pat = _compile(pattern, flags, ignore_unused, kwargs, True)
  275. return pat.subn(repl, string, count, pos, endpos, concurrent, timeout)
  276. def subfn(pattern, format, string, count=0, flags=0, pos=None, endpos=None,
  277. concurrent=None, timeout=None, ignore_unused=False, **kwargs):
  278. """Return a 2-tuple containing (new_string, number). new_string is the string
  279. obtained by replacing the leftmost (or rightmost with a reverse pattern)
  280. non-overlapping occurrences of the pattern in the source string by the
  281. replacement format. number is the number of substitutions that were made. format
  282. can be either a string or a callable; if a string, it's treated as a format
  283. string; if a callable, it's passed the match object and must return a
  284. replacement string to be used."""
  285. pat = _compile(pattern, flags, ignore_unused, kwargs, True)
  286. return pat.subfn(format, string, count, pos, endpos, concurrent, timeout)
  287. def split(pattern, string, maxsplit=0, flags=0, concurrent=None, timeout=None,
  288. ignore_unused=False, **kwargs):
  289. """Split the source string by the occurrences of the pattern, returning a
  290. list containing the resulting substrings. If capturing parentheses are used
  291. in pattern, then the text of all groups in the pattern are also returned as
  292. part of the resulting list. If maxsplit is nonzero, at most maxsplit splits
  293. occur, and the remainder of the string is returned as the final element of
  294. the list."""
  295. pat = _compile(pattern, flags, ignore_unused, kwargs, True)
  296. return pat.split(string, maxsplit, concurrent, timeout)
  297. def splititer(pattern, string, maxsplit=0, flags=0, concurrent=None,
  298. timeout=None, ignore_unused=False, **kwargs):
  299. "Return an iterator yielding the parts of a split string."
  300. pat = _compile(pattern, flags, ignore_unused, kwargs, True)
  301. return pat.splititer(string, maxsplit, concurrent, timeout)
  302. def findall(pattern, string, flags=0, pos=None, endpos=None, overlapped=False,
  303. concurrent=None, timeout=None, ignore_unused=False, **kwargs):
  304. """Return a list of all matches in the string. The matches may be overlapped
  305. if overlapped is True. If one or more groups are present in the pattern,
  306. return a list of groups; this will be a list of tuples if the pattern has
  307. more than one group. Empty matches are included in the result."""
  308. pat = _compile(pattern, flags, ignore_unused, kwargs, True)
  309. return pat.findall(string, pos, endpos, overlapped, concurrent, timeout)
  310. def finditer(pattern, string, flags=0, pos=None, endpos=None, overlapped=False,
  311. partial=False, concurrent=None, timeout=None, ignore_unused=False, **kwargs):
  312. """Return an iterator over all matches in the string. The matches may be
  313. overlapped if overlapped is True. For each match, the iterator returns a
  314. match object. Empty matches are included in the result."""
  315. pat = _compile(pattern, flags, ignore_unused, kwargs, True)
  316. return pat.finditer(string, pos, endpos, overlapped, concurrent, partial,
  317. timeout)
  318. def compile(pattern, flags=0, ignore_unused=False, cache_pattern=None, **kwargs):
  319. "Compile a regular expression pattern, returning a pattern object."
  320. if cache_pattern is None:
  321. cache_pattern = _cache_all
  322. return _compile(pattern, flags, ignore_unused, kwargs, cache_pattern)
  323. def purge():
  324. "Clear the regular expression cache"
  325. _cache.clear()
  326. _locale_sensitive.clear()
  327. # Whether to cache all patterns.
  328. _cache_all = True
  329. def cache_all(value=True):
  330. """Sets whether to cache all patterns, even those are compiled explicitly.
  331. Passing None has no effect, but returns the current setting."""
  332. global _cache_all
  333. if value is None:
  334. return _cache_all
  335. _cache_all = value
  336. def template(pattern, flags=0):
  337. "Compile a template pattern, returning a pattern object."
  338. return _compile(pattern, flags | TEMPLATE, False, {}, False)
  339. def escape(pattern, special_only=True, literal_spaces=False):
  340. """Escape a string for use as a literal in a pattern. If special_only is
  341. True, escape only special characters, else escape all non-alphanumeric
  342. characters. If literal_spaces is True, don't escape spaces."""
  343. # Convert it to Unicode.
  344. if isinstance(pattern, bytes):
  345. p = pattern.decode("latin-1")
  346. else:
  347. p = pattern
  348. s = []
  349. if special_only:
  350. for c in p:
  351. if c == " " and literal_spaces:
  352. s.append(c)
  353. elif c in _METACHARS or c.isspace():
  354. s.append("\\")
  355. s.append(c)
  356. else:
  357. s.append(c)
  358. else:
  359. for c in p:
  360. if c == " " and literal_spaces:
  361. s.append(c)
  362. elif c in _ALNUM:
  363. s.append(c)
  364. else:
  365. s.append("\\")
  366. s.append(c)
  367. r = "".join(s)
  368. # Convert it back to bytes if necessary.
  369. if isinstance(pattern, bytes):
  370. r = r.encode("latin-1")
  371. return r
  372. # --------------------------------------------------------------------
  373. # Internals.
  374. from regex import _regex_core
  375. from regex import _regex
  376. from threading import RLock as _RLock
  377. from locale import getpreferredencoding as _getpreferredencoding
  378. from regex._regex_core import *
  379. from regex._regex_core import (_ALL_VERSIONS, _ALL_ENCODINGS, _FirstSetError,
  380. _UnscopedFlagSet, _check_group_features, _compile_firstset,
  381. _compile_replacement, _flatten_code, _fold_case, _get_required_string,
  382. _parse_pattern, _shrink_cache)
  383. from regex._regex_core import (ALNUM as _ALNUM, Info as _Info, OP as _OP, Source
  384. as _Source, Fuzzy as _Fuzzy)
  385. # Version 0 is the old behaviour, compatible with the original 're' module.
  386. # Version 1 is the new behaviour, which differs slightly.
  387. DEFAULT_VERSION = RegexFlag.VERSION0
  388. _METACHARS = frozenset("()[]{}?*+|^$\\.-#&~")
  389. _regex_core.DEFAULT_VERSION = DEFAULT_VERSION
  390. # Caches for the patterns and replacements.
  391. _cache = {}
  392. _cache_lock = _RLock()
  393. _named_args = {}
  394. _replacement_cache = {}
  395. _locale_sensitive = {}
  396. # Maximum size of the cache.
  397. _MAXCACHE = 500
  398. _MAXREPCACHE = 500
  399. def _compile(pattern, flags, ignore_unused, kwargs, cache_it):
  400. "Compiles a regular expression to a PatternObject."
  401. global DEFAULT_VERSION
  402. try:
  403. from regex import DEFAULT_VERSION
  404. except ImportError:
  405. pass
  406. # We won't bother to cache the pattern if we're debugging.
  407. if (flags & DEBUG) != 0:
  408. cache_it = False
  409. # What locale is this pattern using?
  410. locale_key = (type(pattern), pattern)
  411. if _locale_sensitive.get(locale_key, True) or (flags & LOCALE) != 0:
  412. # This pattern is, or might be, locale-sensitive.
  413. pattern_locale = _getpreferredencoding()
  414. else:
  415. # This pattern is definitely not locale-sensitive.
  416. pattern_locale = None
  417. def complain_unused_args():
  418. if ignore_unused:
  419. return
  420. # Complain about any unused keyword arguments, possibly resulting from a typo.
  421. unused_kwargs = set(kwargs) - {k for k, v in args_needed}
  422. if unused_kwargs:
  423. any_one = next(iter(unused_kwargs))
  424. raise ValueError('unused keyword argument {!a}'.format(any_one))
  425. if cache_it:
  426. try:
  427. # Do we know what keyword arguments are needed?
  428. args_key = pattern, type(pattern), flags
  429. args_needed = _named_args[args_key]
  430. # Are we being provided with its required keyword arguments?
  431. args_supplied = set()
  432. if args_needed:
  433. for k, v in args_needed:
  434. try:
  435. args_supplied.add((k, frozenset(kwargs[k])))
  436. except KeyError:
  437. raise error("missing named list: {!r}".format(k))
  438. complain_unused_args()
  439. args_supplied = frozenset(args_supplied)
  440. # Have we already seen this regular expression and named list?
  441. pattern_key = (pattern, type(pattern), flags, args_supplied,
  442. DEFAULT_VERSION, pattern_locale)
  443. return _cache[pattern_key]
  444. except KeyError:
  445. # It's a new pattern, or new named list for a known pattern.
  446. pass
  447. # Guess the encoding from the class of the pattern string.
  448. if isinstance(pattern, str):
  449. guess_encoding = UNICODE
  450. elif isinstance(pattern, bytes):
  451. guess_encoding = ASCII
  452. elif isinstance(pattern, Pattern):
  453. if flags:
  454. raise ValueError("cannot process flags argument with a compiled pattern")
  455. return pattern
  456. else:
  457. raise TypeError("first argument must be a string or compiled pattern")
  458. # Set the default version in the core code in case it has been changed.
  459. _regex_core.DEFAULT_VERSION = DEFAULT_VERSION
  460. global_flags = flags
  461. while True:
  462. caught_exception = None
  463. try:
  464. source = _Source(pattern)
  465. info = _Info(global_flags, source.char_type, kwargs)
  466. info.guess_encoding = guess_encoding
  467. source.ignore_space = bool(info.flags & VERBOSE)
  468. parsed = _parse_pattern(source, info)
  469. break
  470. except _UnscopedFlagSet:
  471. # Remember the global flags for the next attempt.
  472. global_flags = info.global_flags
  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. if not source.at_end():
  479. raise error("unbalanced parenthesis", pattern, source.pos)
  480. # Check the global flags for conflicts.
  481. version = (info.flags & _ALL_VERSIONS) or DEFAULT_VERSION
  482. if version not in (0, VERSION0, VERSION1):
  483. raise ValueError("VERSION0 and VERSION1 flags are mutually incompatible")
  484. if (info.flags & _ALL_ENCODINGS) not in (0, ASCII, LOCALE, UNICODE):
  485. raise ValueError("ASCII, LOCALE and UNICODE flags are mutually incompatible")
  486. if isinstance(pattern, bytes) and (info.flags & UNICODE):
  487. raise ValueError("cannot use UNICODE flag with a bytes pattern")
  488. if not (info.flags & _ALL_ENCODINGS):
  489. if isinstance(pattern, str):
  490. info.flags |= UNICODE
  491. else:
  492. info.flags |= ASCII
  493. reverse = bool(info.flags & REVERSE)
  494. fuzzy = isinstance(parsed, _Fuzzy)
  495. # Remember whether this pattern as an inline locale flag.
  496. _locale_sensitive[locale_key] = info.inline_locale
  497. # Fix the group references.
  498. caught_exception = None
  499. try:
  500. parsed.fix_groups(pattern, reverse, False)
  501. except error as e:
  502. caught_exception = e
  503. if caught_exception:
  504. raise error(caught_exception.msg, caught_exception.pattern,
  505. caught_exception.pos)
  506. # Should we print the parsed pattern?
  507. if flags & DEBUG:
  508. parsed.dump(indent=0, reverse=reverse)
  509. # Optimise the parsed pattern.
  510. parsed = parsed.optimise(info, reverse)
  511. parsed = parsed.pack_characters(info)
  512. # Get the required string.
  513. req_offset, req_chars, req_flags = _get_required_string(parsed, info.flags)
  514. # Build the named lists.
  515. named_lists = {}
  516. named_list_indexes = [None] * len(info.named_lists_used)
  517. args_needed = set()
  518. for key, index in info.named_lists_used.items():
  519. name, case_flags = key
  520. values = frozenset(kwargs[name])
  521. if case_flags:
  522. items = frozenset(_fold_case(info, v) for v in values)
  523. else:
  524. items = values
  525. named_lists[name] = values
  526. named_list_indexes[index] = items
  527. args_needed.add((name, values))
  528. complain_unused_args()
  529. # Check the features of the groups.
  530. _check_group_features(info, parsed)
  531. # Compile the parsed pattern. The result is a list of tuples.
  532. code = parsed.compile(reverse)
  533. # Is there a group call to the pattern as a whole?
  534. key = (0, reverse, fuzzy)
  535. ref = info.call_refs.get(key)
  536. if ref is not None:
  537. code = [(_OP.CALL_REF, ref)] + code + [(_OP.END, )]
  538. # Add the final 'success' opcode.
  539. code += [(_OP.SUCCESS, )]
  540. # Compile the additional copies of the groups that we need.
  541. for group, rev, fuz in info.additional_groups:
  542. code += group.compile(rev, fuz)
  543. # Flatten the code into a list of ints.
  544. code = _flatten_code(code)
  545. if not parsed.has_simple_start():
  546. # Get the first set, if possible.
  547. try:
  548. fs_code = _compile_firstset(info, parsed.get_firstset(reverse))
  549. fs_code = _flatten_code(fs_code)
  550. code = fs_code + code
  551. except _FirstSetError:
  552. pass
  553. # The named capture groups.
  554. index_group = dict((v, n) for n, v in info.group_index.items())
  555. # Create the PatternObject.
  556. #
  557. # Local flags like IGNORECASE affect the code generation, but aren't needed
  558. # by the PatternObject itself. Conversely, global flags like LOCALE _don't_
  559. # affect the code generation but _are_ needed by the PatternObject.
  560. compiled_pattern = _regex.compile(pattern, info.flags | version, code,
  561. info.group_index, index_group, named_lists, named_list_indexes,
  562. req_offset, req_chars, req_flags, info.group_count)
  563. # Do we need to reduce the size of the cache?
  564. if len(_cache) >= _MAXCACHE:
  565. with _cache_lock:
  566. _shrink_cache(_cache, _named_args, _locale_sensitive, _MAXCACHE)
  567. if cache_it:
  568. if (info.flags & LOCALE) == 0:
  569. pattern_locale = None
  570. args_needed = frozenset(args_needed)
  571. # Store this regular expression and named list.
  572. pattern_key = (pattern, type(pattern), flags, args_needed,
  573. DEFAULT_VERSION, pattern_locale)
  574. _cache[pattern_key] = compiled_pattern
  575. # Store what keyword arguments are needed.
  576. _named_args[args_key] = args_needed
  577. return compiled_pattern
  578. def _compile_replacement_helper(pattern, template):
  579. "Compiles a replacement template."
  580. # This function is called by the _regex module.
  581. # Have we seen this before?
  582. key = pattern.pattern, pattern.flags, template
  583. compiled = _replacement_cache.get(key)
  584. if compiled is not None:
  585. return compiled
  586. if len(_replacement_cache) >= _MAXREPCACHE:
  587. _replacement_cache.clear()
  588. is_unicode = isinstance(template, str)
  589. source = _Source(template)
  590. if is_unicode:
  591. def make_string(char_codes):
  592. return "".join(chr(c) for c in char_codes)
  593. else:
  594. def make_string(char_codes):
  595. return bytes(char_codes)
  596. compiled = []
  597. literal = []
  598. while True:
  599. ch = source.get()
  600. if not ch:
  601. break
  602. if ch == "\\":
  603. # '_compile_replacement' will return either an int group reference
  604. # or a string literal. It returns items (plural) in order to handle
  605. # a 2-character literal (an invalid escape sequence).
  606. is_group, items = _compile_replacement(source, pattern, is_unicode)
  607. if is_group:
  608. # It's a group, so first flush the literal.
  609. if literal:
  610. compiled.append(make_string(literal))
  611. literal = []
  612. compiled.extend(items)
  613. else:
  614. literal.extend(items)
  615. else:
  616. literal.append(ord(ch))
  617. # Flush the literal.
  618. if literal:
  619. compiled.append(make_string(literal))
  620. _replacement_cache[key] = compiled
  621. return compiled
  622. # We define Pattern here after all the support objects have been defined.
  623. _pat = _compile('', 0, False, {}, False)
  624. Pattern = type(_pat)
  625. Match = type(_pat.match(''))
  626. del _pat
  627. # Make Pattern public for typing annotations.
  628. __all__.append("Pattern")
  629. __all__.append("Match")
  630. # We'll define an alias for the 'compile' function so that the repr of a
  631. # pattern object is eval-able.
  632. Regex = compile
  633. # Register myself for pickling.
  634. import copyreg as _copy_reg
  635. def _pickle(pattern):
  636. return _regex.compile, pattern._pickled_data
  637. _copy_reg.pickle(Pattern, _pickle)