blob: addd106b1c26532c57329f2c49df5d8aa4440e0d [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 Drakeb8f22742001-09-04 19:10:20 +000017"""Support for regular expressions (RE).
18
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.
48 (?iLmsx) Set the I, L, M, S, or X flag for the RE.
49 (?:...) 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.
59 \\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_].
69 With LOCALE, it will match the set [0-9_] plus characters defined
70 as letters for the current locale.
71 \\W Matches the complement of \\w.
72 \\\\ Matches a literal backslash.
73
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.
83 template Compile a template pattern, returning a pattern object.
84 escape Backslash all non-alphanumerics in a string.
85
86Some of the functions in this module takes flags as optional parameters:
87 I IGNORECASE Perform case-insensitive matching.
88 L LOCALE Make \w, \W, \b, \B, dependent on the current locale.
89 M MULTILINE "^" matches the beginning of lines as well as the string.
90 "$" matches the end of lines as well as the string.
91 S DOTALL "." matches any character at all, including the newline.
92 X VERBOSE Ignore whitespace and comments for nicer looking RE's.
93 U UNICODE Use unicode locale.
94
95This module also defines an exception 'error'.
96
97"""
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 Lundhb25e1ad2001-03-22 15:50:10 +0000107__version__ = "2.1b2"
108
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
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000200_MAXCACHE = 100
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000201
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000202def _join(seq, sep):
203 # internal: join into string having the same type as sep
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000204 return string.join(seq, sep[:0])
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000205
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000206def _compile(*key):
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000207 # internal: compile pattern
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000208 p = _cache.get(key)
209 if p is not None:
210 return p
211 pattern, flags = key
212 if type(pattern) not in sre_compile.STRING_TYPES:
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000213 return pattern
Fredrik Lundhe1869832000-08-01 22:47:49 +0000214 try:
215 p = sre_compile.compile(pattern, flags)
216 except error, v:
217 raise error, v # invalid expression
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000218 if len(_cache) >= _MAXCACHE:
219 _cache.clear()
220 _cache[key] = p
221 return p
222
Fredrik Lundhb25e1ad2001-03-22 15:50:10 +0000223def _compile_repl(*key):
224 # internal: compile replacement pattern
225 p = _cache_repl.get(key)
226 if p is not None:
227 return p
228 repl, pattern = key
229 try:
230 p = sre_parse.parse_template(repl, pattern)
231 except error, v:
232 raise error, v # invalid expression
233 if len(_cache_repl) >= _MAXCACHE:
234 _cache_repl.clear()
235 _cache_repl[key] = p
236 return p
237
Fredrik Lundh5644b7f2000-09-21 17:03:25 +0000238def _expand(pattern, match, template):
239 # internal: match.expand implementation hook
240 template = sre_parse.parse_template(template, pattern)
241 return sre_parse.expand_template(template, match)
242
Fredrik Lundh2d96f112001-07-08 13:26:57 +0000243def _sub(pattern, template, text, count=0):
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000244 # internal: pattern.sub implementation hook
Fredrik Lundh2d96f112001-07-08 13:26:57 +0000245 return _subn(pattern, template, text, count, 1)[0]
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000246
Fredrik Lundh2d96f112001-07-08 13:26:57 +0000247def _subn(pattern, template, text, count=0, sub=0):
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000248 # internal: pattern.subn implementation hook
249 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 Lundh2d96f112001-07-08 13:26:57 +0000253 literals = template[1]
Guido van Rossum315cd292001-08-10 14:56:54 +0000254 sub = 0 # temporarly disabled, see bug #449000
Fredrik Lundh2d96f112001-07-08 13:26:57 +0000255 if (sub and not count and pattern._isliteral() and
256 len(literals) == 1 and literals[0]):
257 # shortcut: both pattern and string are literals
258 return string.replace(text, pattern.pattern, literals[0]), 0
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000259 def filter(match, template=template):
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000260 return sre_parse.expand_template(template, match)
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000261 n = i = 0
262 s = []
263 append = s.append
Fredrik Lundh2d96f112001-07-08 13:26:57 +0000264 c = pattern.scanner(text)
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000265 while not count or n < count:
266 m = c.search()
267 if not m:
268 break
Fredrik Lundh90a07912000-06-30 07:50:59 +0000269 b, e = m.span()
Fredrik Lundh01016fe2000-06-30 00:27:46 +0000270 if i < b:
Fredrik Lundh2d96f112001-07-08 13:26:57 +0000271 append(text[i:b])
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000272 append(filter(m))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000273 i = e
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000274 n = n + 1
Fredrik Lundh2d96f112001-07-08 13:26:57 +0000275 append(text[i:])
276 return _join(s, text[:0]), n
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000277
Fredrik Lundh2d96f112001-07-08 13:26:57 +0000278def _split(pattern, text, maxsplit=0):
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000279 # internal: pattern.split implementation hook
280 n = i = 0
281 s = []
282 append = s.append
Fredrik Lundhbe2211e2000-06-29 16:57:40 +0000283 extend = s.extend
Fredrik Lundh2d96f112001-07-08 13:26:57 +0000284 c = pattern.scanner(text)
Fredrik Lundh01016fe2000-06-30 00:27:46 +0000285 g = pattern.groups
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000286 while not maxsplit or n < maxsplit:
287 m = c.search()
288 if not m:
289 break
Fredrik Lundh90a07912000-06-30 07:50:59 +0000290 b, e = m.span()
291 if b == e:
Fredrik Lundh2d96f112001-07-08 13:26:57 +0000292 if i >= len(text):
Fredrik Lundh90a07912000-06-30 07:50:59 +0000293 break
294 continue
Fredrik Lundh2d96f112001-07-08 13:26:57 +0000295 append(text[i:b])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000296 if g and b != e:
Fredrik Lundh1c5aa692001-01-16 07:37:30 +0000297 extend(list(m.groups()))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000298 i = e
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000299 n = n + 1
Fredrik Lundh2d96f112001-07-08 13:26:57 +0000300 append(text[i:])
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000301 return s
Fredrik Lundh0640e112000-06-30 13:55:15 +0000302
303# register myself for pickling
304
305import copy_reg
306
307def _pickle(p):
308 return _compile, (p.pattern, p.flags)
309
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000310copy_reg.pickle(type(_compile("", 0)), _pickle, _compile)
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000311
312# --------------------------------------------------------------------
313# experimental stuff (see python-dev discussions for details)
314
315class Scanner:
316 def __init__(self, lexicon):
Fredrik Lundh29c4ba92000-08-01 18:20:07 +0000317 from sre_constants import BRANCH, SUBPATTERN
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000318 self.lexicon = lexicon
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000319 # combine phrases into a compound pattern
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000320 p = []
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000321 s = sre_parse.Pattern()
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000322 for phrase, action in lexicon:
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000323 p.append(sre_parse.SubPattern(s, [
Fredrik Lundh29c4ba92000-08-01 18:20:07 +0000324 (SUBPATTERN, (len(p), sre_parse.parse(phrase))),
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000325 ]))
326 p = sre_parse.SubPattern(s, [(BRANCH, (None, p))])
327 s.groups = len(p)
328 self.scanner = sre_compile.compile(p)
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000329 def scan(self, string):
330 result = []
331 append = result.append
332 match = self.scanner.match
333 i = 0
334 while 1:
335 m = match(string, i)
336 if not m:
337 break
338 j = m.end()
339 if i == j:
340 break
Fredrik Lundh019bcb52000-07-02 22:59:57 +0000341 action = self.lexicon[m.lastindex][1]
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000342 if callable(action):
Fredrik Lundh770617b2001-01-14 15:06:11 +0000343 self.match = m
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000344 action = action(self, m.group())
345 if action is not None:
346 append(action)
347 i = j
348 return result, string[i:]