blob: 701334e5db113430307d641e9c3e03bb3714684c [file] [log] [blame]
Guido van Rossum7627c0d2000-03-31 14:58:54 +00001#
2# Secret Labs' Regular Expression Engine
Guido van Rossum7627c0d2000-03-31 14:58:54 +00003#
4# re-compatible interface for the sre matching engine
5#
Fredrik Lundh770617b2001-01-14 15:06:11 +00006# Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved.
Guido van Rossum7627c0d2000-03-31 14:58:54 +00007#
Fredrik Lundh29c4ba92000-08-01 18:20:07 +00008# This version of the SRE library can be redistributed under CNRI's
9# Python 1.6 license. For any other use, please contact Secret Labs
10# AB (info@pythonware.com).
11#
Guido van Rossum7627c0d2000-03-31 14:58:54 +000012# Portions of this engine have been developed in cooperation with
Fredrik Lundh29c4ba92000-08-01 18:20:07 +000013# CNRI. Hewlett-Packard provided funding for 1.6 integration and
Guido van Rossum7627c0d2000-03-31 14:58:54 +000014# other compatibility work.
15#
16
Fred Drake9f5b8222001-09-04 19:20:06 +000017r"""Support for regular expressions (RE).
Fred Drakeb8f22742001-09-04 19:10:20 +000018
19This module provides regular expression matching operations similar to
20those found in Perl. It's 8-bit clean: the strings being processed may
21contain both null bytes and characters whose high bit is set. Regular
22expression pattern strings may not contain null bytes, but can specify
23the null byte using the \\number notation. Characters with the high
24bit set may be included.
25
26Regular expressions can contain both special and ordinary
27characters. Most ordinary characters, like "A", "a", or "0", are the
28simplest regular expressions; they simply match themselves. You can
29concatenate ordinary characters, so last matches the string 'last'.
30
31The special characters are:
32 "." Matches any character except a newline.
33 "^" Matches the start of the string.
34 "$" Matches the end of the string.
35 "*" Matches 0 or more (greedy) repetitions of the preceding RE.
36 Greedy means that it will match as many repetitions as possible.
37 "+" Matches 1 or more (greedy) repetitions of the preceding RE.
38 "?" Matches 0 or 1 (greedy) of the preceding RE.
39 *?,+?,?? Non-greedy versions of the previous three special characters.
40 {m,n} Matches from m to n repetitions of the preceding RE.
41 {m,n}? Non-greedy version of the above.
42 "\\" Either escapes special characters or signals a special sequence.
43 [] Indicates a set of characters.
44 A "^" as the first character indicates a complementing set.
45 "|" A|B, creates an RE that will match either A or B.
46 (...) Matches the RE inside the parentheses.
47 The contents can be retrieved or matched later in the string.
Fredrik Lundh21009b92001-09-18 18:47:09 +000048 (?iLmsx) Set the I, L, M, S, or X flag for the RE (see below).
Fred Drakeb8f22742001-09-04 19:10:20 +000049 (?:...) Non-grouping version of regular parentheses.
50 (?P<name>...) The substring matched by the group is accessible by name.
51 (?P=name) Matches the text matched earlier by the group named name.
52 (?#...) A comment; ignored.
53 (?=...) Matches if ... matches next, but doesn't consume the string.
54 (?!...) Matches if ... doesn't match next.
55
56The special sequences consist of "\\" and a character from the list
57below. If the ordinary character is not on the list, then the
58resulting RE will match the second character.
Fred Drake9f5b8222001-09-04 19:20:06 +000059 \number Matches the contents of the group of the same number.
60 \A Matches only at the start of the string.
61 \Z Matches only at the end of the string.
62 \b Matches the empty string, but only at the start or end of a word.
63 \B Matches the empty string, but not at the start or end of a word.
64 \d Matches any decimal digit; equivalent to the set [0-9].
65 \D Matches any non-digit character; equivalent to the set [^0-9].
66 \s Matches any whitespace character; equivalent to [ \t\n\r\f\v].
67 \S Matches any non-whitespace character; equiv. to [^ \t\n\r\f\v].
68 \w Matches any alphanumeric character; equivalent to [a-zA-Z0-9_].
Fred Drakeb8f22742001-09-04 19:10:20 +000069 With LOCALE, it will match the set [0-9_] plus characters defined
70 as letters for the current locale.
Fred Drake9f5b8222001-09-04 19:20:06 +000071 \W Matches the complement of \w.
72 \\ Matches a literal backslash.
Fred Drakeb8f22742001-09-04 19:10:20 +000073
74This module exports the following functions:
75 match Match a regular expression pattern to the beginning of a string.
76 search Search a string for the presence of a pattern.
77 sub Substitute occurrences of a pattern found in a string.
78 subn Same as sub, but also return the number of substitutions made.
79 split Split a string by the occurrences of a pattern.
80 findall Find all occurrences of a pattern in a string.
81 compile Compile a pattern into a RegexObject.
82 purge Clear the regular expression cache.
Fred Drakeb8f22742001-09-04 19:10:20 +000083 escape Backslash all non-alphanumerics in a string.
84
85Some of the functions in this module takes flags as optional parameters:
86 I IGNORECASE Perform case-insensitive matching.
87 L LOCALE Make \w, \W, \b, \B, dependent on the current locale.
88 M MULTILINE "^" matches the beginning of lines as well as the string.
89 "$" matches the end of lines as well as the string.
90 S DOTALL "." matches any character at all, including the newline.
91 X VERBOSE Ignore whitespace and comments for nicer looking RE's.
Fredrik Lundh21009b92001-09-18 18:47:09 +000092 U UNICODE Make \w, \W, \b, \B, dependent on the Unicode locale.
Fred Drakeb8f22742001-09-04 19:10:20 +000093
94This module also defines an exception 'error'.
95
96"""
Fredrik Lundh21009b92001-09-18 18:47:09 +000097
Guido van Rossum7627c0d2000-03-31 14:58:54 +000098import sre_compile
Fredrik Lundh436c3d582000-06-29 08:58:44 +000099import sre_parse
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000100
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000101# public symbols
102__all__ = [ "match", "search", "sub", "subn", "split", "findall",
103 "compile", "purge", "template", "escape", "I", "L", "M", "S", "X",
104 "U", "IGNORECASE", "LOCALE", "MULTILINE", "DOTALL", "VERBOSE",
105 "UNICODE", "error" ]
106
Fredrik Lundhbec95b92001-10-21 16:47:57 +0000107__version__ = "2.2.1"
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000108
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000109# this module works under 1.5.2 and later. don't use string methods
110import string
Skip Montanaro0de65802001-02-15 22:15:14 +0000111
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000112# flags
Fredrik Lundh770617b2001-01-14 15:06:11 +0000113I = IGNORECASE = sre_compile.SRE_FLAG_IGNORECASE # ignore case
114L = LOCALE = sre_compile.SRE_FLAG_LOCALE # assume current 8-bit locale
115U = UNICODE = sre_compile.SRE_FLAG_UNICODE # assume unicode locale
116M = MULTILINE = sre_compile.SRE_FLAG_MULTILINE # make anchors look for newline
117S = DOTALL = sre_compile.SRE_FLAG_DOTALL # make dot match newline
118X = VERBOSE = sre_compile.SRE_FLAG_VERBOSE # ignore whitespace and comments
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000119
Fredrik Lundh770617b2001-01-14 15:06:11 +0000120# sre extensions (experimental, don't rely on these)
121T = TEMPLATE = sre_compile.SRE_FLAG_TEMPLATE # disable backtracking
122DEBUG = sre_compile.SRE_FLAG_DEBUG # dump pattern after compilation
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000123
124# sre exception
Fredrik Lundhbe2211e2000-06-29 16:57:40 +0000125error = sre_compile.error
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000126
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000127# --------------------------------------------------------------------
128# public interface
129
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000130def match(pattern, string, flags=0):
Fredrik Lundh770617b2001-01-14 15:06:11 +0000131 """Try to apply the pattern at the start of the string, returning
132 a match object, or None if no match was found."""
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000133 return _compile(pattern, flags).match(string)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000134
135def search(pattern, string, flags=0):
Fredrik Lundh770617b2001-01-14 15:06:11 +0000136 """Scan through string looking for a match to the pattern, returning
137 a match object, or None if no match was found."""
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000138 return _compile(pattern, flags).search(string)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000139
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000140def sub(pattern, repl, string, count=0):
Fredrik Lundh770617b2001-01-14 15:06:11 +0000141 """Return the string obtained by replacing the leftmost
142 non-overlapping occurrences of the pattern in string by the
143 replacement repl"""
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000144 return _compile(pattern, 0).sub(repl, string, count)
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000145
146def subn(pattern, repl, string, count=0):
Fredrik Lundh770617b2001-01-14 15:06:11 +0000147 """Return a 2-tuple containing (new_string, number).
148 new_string is the string obtained by replacing the leftmost
149 non-overlapping occurrences of the pattern in the source
150 string by the replacement repl. number is the number of
151 substitutions that were made."""
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000152 return _compile(pattern, 0).subn(repl, string, count)
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000153
154def split(pattern, string, maxsplit=0):
Fredrik Lundh770617b2001-01-14 15:06:11 +0000155 """Split the source string by the occurrences of the pattern,
156 returning a list containing the resulting substrings."""
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000157 return _compile(pattern, 0).split(string, maxsplit)
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000158
Fredrik Lundhe06cbb82001-07-06 20:56:10 +0000159def findall(pattern, string):
Fredrik Lundh770617b2001-01-14 15:06:11 +0000160 """Return a list of all non-overlapping matches in the string.
161
162 If one or more groups are present in the pattern, return a
163 list of groups; this will be a list of tuples if the pattern
164 has more than one group.
165
166 Empty matches are included in the result."""
Fredrik Lundhe06cbb82001-07-06 20:56:10 +0000167 return _compile(pattern, 0).findall(string)
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000168
169def compile(pattern, flags=0):
Fredrik Lundh770617b2001-01-14 15:06:11 +0000170 "Compile a regular expression pattern, returning a pattern object."
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000171 return _compile(pattern, flags)
172
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000173def purge():
Fredrik Lundh770617b2001-01-14 15:06:11 +0000174 "Clear the regular expression cache"
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000175 _cache.clear()
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000176 _cache_repl.clear()
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000177
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000178def template(pattern, flags=0):
Fredrik Lundh770617b2001-01-14 15:06:11 +0000179 "Compile a template pattern, returning a pattern object"
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000180 return _compile(pattern, flags|T)
181
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000182def escape(pattern):
Fredrik Lundh770617b2001-01-14 15:06:11 +0000183 "Escape all non-alphanumeric characters in pattern."
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000184 s = list(pattern)
185 for i in range(len(pattern)):
186 c = pattern[i]
187 if not ("a" <= c <= "z" or "A" <= c <= "Z" or "0" <= c <= "9"):
188 if c == "\000":
189 s[i] = "\\000"
190 else:
191 s[i] = "\\" + c
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000192 return _join(s, pattern)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000193
194# --------------------------------------------------------------------
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000195# internals
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000196
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000197_cache = {}
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000198_cache_repl = {}
199
Fredrik Lundh397a6542001-10-18 19:30:16 +0000200_pattern_type = type(sre_compile.compile("", 0))
201
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000202_MAXCACHE = 100
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000203
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000204def _join(seq, sep):
205 # internal: join into string having the same type as sep
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000206 return string.join(seq, sep[:0])
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000207
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000208def _compile(*key):
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000209 # internal: compile pattern
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000210 p = _cache.get(key)
211 if p is not None:
212 return p
213 pattern, flags = key
Fredrik Lundh397a6542001-10-18 19:30:16 +0000214 if type(pattern) is _pattern_type:
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000215 return pattern
Fredrik Lundh397a6542001-10-18 19:30:16 +0000216 if type(pattern) not in sre_compile.STRING_TYPES:
217 raise TypeError, "first argument must be string or compiled pattern"
Fredrik Lundhe1869832000-08-01 22:47:49 +0000218 try:
219 p = sre_compile.compile(pattern, flags)
220 except error, v:
221 raise error, v # invalid expression
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000222 if len(_cache) >= _MAXCACHE:
223 _cache.clear()
224 _cache[key] = p
225 return p
226
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000227def _compile_repl(*key):
228 # internal: compile replacement pattern
229 p = _cache_repl.get(key)
230 if p is not None:
231 return p
232 repl, pattern = key
233 try:
234 p = sre_parse.parse_template(repl, pattern)
235 except error, v:
236 raise error, v # invalid expression
237 if len(_cache_repl) >= _MAXCACHE:
238 _cache_repl.clear()
239 _cache_repl[key] = p
240 return p
241
Fredrik Lundh5644b7f2000-09-21 17:03:25 +0000242def _expand(pattern, match, template):
243 # internal: match.expand implementation hook
244 template = sre_parse.parse_template(template, pattern)
245 return sre_parse.expand_template(template, match)
246
Fredrik Lundhbec95b92001-10-21 16:47:57 +0000247def _subx(pattern, template):
248 # internal: pattern.sub/subn implementation helper
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000249 if callable(template):
Andrew M. Kuchlinge8d52af2000-06-18 20:27:10 +0000250 filter = template
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000251 else:
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000252 template = _compile_repl(template, pattern)
Fredrik Lundhbec95b92001-10-21 16:47:57 +0000253 if not template[0] and len(template[1]) == 1:
254 # literal replacement
255 filter = template[1][0]
256 else:
257 def filter(match, template=template):
258 return sre_parse.expand_template(template, match)
259 return filter
260
261def _sub(pattern, template, text, count=0):
262 # internal: pattern.sub implementation hook
263 # FIXME: not used in SRE 2.2.1 and later; will be removed soon
264 return _subn(pattern, template, text, count)[0]
265
266def _subn(pattern, template, text, count=0):
267 # internal: pattern.subn implementation hook
268 # FIXME: not used in SRE 2.2.1 and later; will be removed soon
269 filter = _subx(pattern, template)
270 if not callable(filter):
271 # literal replacement
272 def filter(match, literal=filter):
273 return literal
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000274 n = i = 0
275 s = []
276 append = s.append
Fredrik Lundh2d96f112001-07-08 13:26:57 +0000277 c = pattern.scanner(text)
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000278 while not count or n < count:
279 m = c.search()
280 if not m:
281 break
Fredrik Lundh90a07912000-06-30 07:50:59 +0000282 b, e = m.span()
Fredrik Lundh01016fe2000-06-30 00:27:46 +0000283 if i < b:
Fredrik Lundh2d96f112001-07-08 13:26:57 +0000284 append(text[i:b])
Fredrik Lundh21009b92001-09-18 18:47:09 +0000285 elif i == b == e and n:
286 append(text[i:b])
287 continue # ignore empty match at previous position
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000288 append(filter(m))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000289 i = e
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000290 n = n + 1
Fredrik Lundh2d96f112001-07-08 13:26:57 +0000291 append(text[i:])
292 return _join(s, text[:0]), n
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000293
Fredrik Lundh2d96f112001-07-08 13:26:57 +0000294def _split(pattern, text, maxsplit=0):
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000295 # internal: pattern.split implementation hook
Fredrik Lundhbec95b92001-10-21 16:47:57 +0000296 # FIXME: not used in SRE 2.2.1 and later; will be removed soon
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000297 n = i = 0
298 s = []
299 append = s.append
Fredrik Lundhbe2211e2000-06-29 16:57:40 +0000300 extend = s.extend
Fredrik Lundh2d96f112001-07-08 13:26:57 +0000301 c = pattern.scanner(text)
Fredrik Lundh01016fe2000-06-30 00:27:46 +0000302 g = pattern.groups
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000303 while not maxsplit or n < maxsplit:
304 m = c.search()
305 if not m:
306 break
Fredrik Lundh90a07912000-06-30 07:50:59 +0000307 b, e = m.span()
308 if b == e:
Fredrik Lundh2d96f112001-07-08 13:26:57 +0000309 if i >= len(text):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000310 break
311 continue
Fredrik Lundh2d96f112001-07-08 13:26:57 +0000312 append(text[i:b])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000313 if g and b != e:
Fredrik Lundh1c5aa692001-01-16 07:37:30 +0000314 extend(list(m.groups()))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000315 i = e
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000316 n = n + 1
Fredrik Lundh2d96f112001-07-08 13:26:57 +0000317 append(text[i:])
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000318 return s
Fredrik Lundh0640e112000-06-30 13:55:15 +0000319
320# register myself for pickling
321
322import copy_reg
323
324def _pickle(p):
325 return _compile, (p.pattern, p.flags)
326
Fredrik Lundh397a6542001-10-18 19:30:16 +0000327copy_reg.pickle(_pattern_type, _pickle, _compile)
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000328
329# --------------------------------------------------------------------
330# experimental stuff (see python-dev discussions for details)
331
332class Scanner:
Fredrik Lundh1296a8d2001-10-21 18:04:11 +0000333 def __init__(self, lexicon, flags=0):
Fredrik Lundh29c4ba92000-08-01 18:20:07 +0000334 from sre_constants import BRANCH, SUBPATTERN
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000335 self.lexicon = lexicon
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000336 # combine phrases into a compound pattern
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000337 p = []
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000338 s = sre_parse.Pattern()
Fredrik Lundh1296a8d2001-10-21 18:04:11 +0000339 s.flags = flags
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000340 for phrase, action in lexicon:
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000341 p.append(sre_parse.SubPattern(s, [
Fredrik Lundh1296a8d2001-10-21 18:04:11 +0000342 (SUBPATTERN, (len(p)+1, sre_parse.parse(phrase, flags))),
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000343 ]))
344 p = sre_parse.SubPattern(s, [(BRANCH, (None, p))])
345 s.groups = len(p)
346 self.scanner = sre_compile.compile(p)
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000347 def scan(self, string):
348 result = []
349 append = result.append
Fredrik Lundh1296a8d2001-10-21 18:04:11 +0000350 match = self.scanner.scanner(string).match
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000351 i = 0
352 while 1:
Fredrik Lundh1296a8d2001-10-21 18:04:11 +0000353 m = match()
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000354 if not m:
355 break
356 j = m.end()
357 if i == j:
358 break
Fredrik Lundh1296a8d2001-10-21 18:04:11 +0000359 action = self.lexicon[m.lastindex-1][1]
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000360 if callable(action):
Fredrik Lundh770617b2001-01-14 15:06:11 +0000361 self.match = m
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000362 action = action(self, m.group())
363 if action is not None:
364 append(action)
365 i = j
366 return result, string[i:]