blob: 48d390a5ec5ac24fb8fcd2377d0377b7da191a62 [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
Guido van Rossum7627c0d2000-03-31 14:58:54 +000017import sre_compile
Fredrik Lundh436c3d52000-06-29 08:58:44 +000018import sre_parse
Guido van Rossum7627c0d2000-03-31 14:58:54 +000019
Fredrik Lundhf2989b22001-02-18 12:05:16 +000020# public symbols
21__all__ = [ "match", "search", "sub", "subn", "split", "findall",
22 "compile", "purge", "template", "escape", "I", "L", "M", "S", "X",
23 "U", "IGNORECASE", "LOCALE", "MULTILINE", "DOTALL", "VERBOSE",
24 "UNICODE", "error" ]
25
26# this module works under 1.5.2 and later. don't use string methods
27import string
Skip Montanaro0de65802001-02-15 22:15:14 +000028
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +000029# flags
Fredrik Lundh770617b2001-01-14 15:06:11 +000030I = IGNORECASE = sre_compile.SRE_FLAG_IGNORECASE # ignore case
31L = LOCALE = sre_compile.SRE_FLAG_LOCALE # assume current 8-bit locale
32U = UNICODE = sre_compile.SRE_FLAG_UNICODE # assume unicode locale
33M = MULTILINE = sre_compile.SRE_FLAG_MULTILINE # make anchors look for newline
34S = DOTALL = sre_compile.SRE_FLAG_DOTALL # make dot match newline
35X = VERBOSE = sre_compile.SRE_FLAG_VERBOSE # ignore whitespace and comments
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +000036
Fredrik Lundh770617b2001-01-14 15:06:11 +000037# sre extensions (experimental, don't rely on these)
38T = TEMPLATE = sre_compile.SRE_FLAG_TEMPLATE # disable backtracking
39DEBUG = sre_compile.SRE_FLAG_DEBUG # dump pattern after compilation
Fredrik Lundh436c3d52000-06-29 08:58:44 +000040
41# sre exception
Fredrik Lundhbe2211e2000-06-29 16:57:40 +000042error = sre_compile.error
Fredrik Lundh436c3d52000-06-29 08:58:44 +000043
Guido van Rossum7627c0d2000-03-31 14:58:54 +000044# --------------------------------------------------------------------
45# public interface
46
Guido van Rossum7627c0d2000-03-31 14:58:54 +000047def match(pattern, string, flags=0):
Fredrik Lundh770617b2001-01-14 15:06:11 +000048 """Try to apply the pattern at the start of the string, returning
49 a match object, or None if no match was found."""
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +000050 return _compile(pattern, flags).match(string)
Guido van Rossum7627c0d2000-03-31 14:58:54 +000051
52def search(pattern, string, flags=0):
Fredrik Lundh770617b2001-01-14 15:06:11 +000053 """Scan through string looking for a match to the pattern, returning
54 a match object, or None if no match was found."""
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +000055 return _compile(pattern, flags).search(string)
Guido van Rossum7627c0d2000-03-31 14:58:54 +000056
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +000057def sub(pattern, repl, string, count=0):
Fredrik Lundh770617b2001-01-14 15:06:11 +000058 """Return the string obtained by replacing the leftmost
59 non-overlapping occurrences of the pattern in string by the
60 replacement repl"""
Fredrik Lundh7898c3e2000-08-07 20:59:04 +000061 return _compile(pattern, 0).sub(repl, string, count)
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +000062
63def subn(pattern, repl, string, count=0):
Fredrik Lundh770617b2001-01-14 15:06:11 +000064 """Return a 2-tuple containing (new_string, number).
65 new_string is the string obtained by replacing the leftmost
66 non-overlapping occurrences of the pattern in the source
67 string by the replacement repl. number is the number of
68 substitutions that were made."""
Fredrik Lundh7898c3e2000-08-07 20:59:04 +000069 return _compile(pattern, 0).subn(repl, string, count)
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +000070
71def split(pattern, string, maxsplit=0):
Fredrik Lundh770617b2001-01-14 15:06:11 +000072 """Split the source string by the occurrences of the pattern,
73 returning a list containing the resulting substrings."""
Fredrik Lundh7898c3e2000-08-07 20:59:04 +000074 return _compile(pattern, 0).split(string, maxsplit)
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +000075
76def findall(pattern, string, maxsplit=0):
Fredrik Lundh770617b2001-01-14 15:06:11 +000077 """Return a list of all non-overlapping matches in the string.
78
79 If one or more groups are present in the pattern, return a
80 list of groups; this will be a list of tuples if the pattern
81 has more than one group.
82
83 Empty matches are included in the result."""
Fredrik Lundh7898c3e2000-08-07 20:59:04 +000084 return _compile(pattern, 0).findall(string, maxsplit)
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +000085
86def compile(pattern, flags=0):
Fredrik Lundh770617b2001-01-14 15:06:11 +000087 "Compile a regular expression pattern, returning a pattern object."
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +000088 return _compile(pattern, flags)
89
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000090def purge():
Fredrik Lundh770617b2001-01-14 15:06:11 +000091 "Clear the regular expression cache"
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000092 _cache.clear()
93
Fredrik Lundh436c3d52000-06-29 08:58:44 +000094def template(pattern, flags=0):
Fredrik Lundh770617b2001-01-14 15:06:11 +000095 "Compile a template pattern, returning a pattern object"
Fredrik Lundh436c3d52000-06-29 08:58:44 +000096 return _compile(pattern, flags|T)
97
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +000098def escape(pattern):
Fredrik Lundh770617b2001-01-14 15:06:11 +000099 "Escape all non-alphanumeric characters in pattern."
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000100 s = list(pattern)
101 for i in range(len(pattern)):
102 c = pattern[i]
103 if not ("a" <= c <= "z" or "A" <= c <= "Z" or "0" <= c <= "9"):
104 if c == "\000":
105 s[i] = "\\000"
106 else:
107 s[i] = "\\" + c
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000108 return _join(s, pattern)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000109
110# --------------------------------------------------------------------
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000111# internals
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000112
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000113_cache = {}
114_MAXCACHE = 100
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000115
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000116def _join(seq, sep):
117 # internal: join into string having the same type as sep
Fredrik Lundhf2989b22001-02-18 12:05:16 +0000118 return string.join(seq, sep[:0])
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000119
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000120def _compile(*key):
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000121 # internal: compile pattern
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000122 p = _cache.get(key)
123 if p is not None:
124 return p
125 pattern, flags = key
126 if type(pattern) not in sre_compile.STRING_TYPES:
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000127 return pattern
Fredrik Lundhe1869832000-08-01 22:47:49 +0000128 try:
129 p = sre_compile.compile(pattern, flags)
130 except error, v:
131 raise error, v # invalid expression
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000132 if len(_cache) >= _MAXCACHE:
133 _cache.clear()
134 _cache[key] = p
135 return p
136
Fredrik Lundh5644b7f2000-09-21 17:03:25 +0000137def _expand(pattern, match, template):
138 # internal: match.expand implementation hook
139 template = sre_parse.parse_template(template, pattern)
140 return sre_parse.expand_template(template, match)
141
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000142def _sub(pattern, template, string, count=0):
143 # internal: pattern.sub implementation hook
144 return _subn(pattern, template, string, count)[0]
145
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000146def _subn(pattern, template, string, count=0):
147 # internal: pattern.subn implementation hook
148 if callable(template):
Andrew M. Kuchlinge8d52af2000-06-18 20:27:10 +0000149 filter = template
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000150 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000151 template = sre_parse.parse_template(template, pattern)
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000152 def filter(match, template=template):
Fredrik Lundh436c3d52000-06-29 08:58:44 +0000153 return sre_parse.expand_template(template, match)
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000154 n = i = 0
155 s = []
156 append = s.append
Fredrik Lundhbe2211e2000-06-29 16:57:40 +0000157 c = pattern.scanner(string)
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000158 while not count or n < count:
159 m = c.search()
160 if not m:
161 break
Fredrik Lundh90a07912000-06-30 07:50:59 +0000162 b, e = m.span()
Fredrik Lundh01016fe2000-06-30 00:27:46 +0000163 if i < b:
164 append(string[i:b])
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000165 append(filter(m))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000166 i = e
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000167 n = n + 1
Fredrik Lundh01016fe2000-06-30 00:27:46 +0000168 append(string[i:])
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000169 return _join(s, string[:0]), n
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000170
171def _split(pattern, string, maxsplit=0):
172 # internal: pattern.split implementation hook
173 n = i = 0
174 s = []
175 append = s.append
Fredrik Lundhbe2211e2000-06-29 16:57:40 +0000176 extend = s.extend
177 c = pattern.scanner(string)
Fredrik Lundh01016fe2000-06-30 00:27:46 +0000178 g = pattern.groups
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000179 while not maxsplit or n < maxsplit:
180 m = c.search()
181 if not m:
182 break
Fredrik Lundh90a07912000-06-30 07:50:59 +0000183 b, e = m.span()
184 if b == e:
185 if i >= len(string):
186 break
187 continue
Fredrik Lundhbe2211e2000-06-29 16:57:40 +0000188 append(string[i:b])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000189 if g and b != e:
Fredrik Lundh1c5aa692001-01-16 07:37:30 +0000190 extend(list(m.groups()))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000191 i = e
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000192 n = n + 1
Fredrik Lundh80946112000-06-29 18:03:25 +0000193 append(string[i:])
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000194 return s
Fredrik Lundh0640e112000-06-30 13:55:15 +0000195
196# register myself for pickling
197
198import copy_reg
199
200def _pickle(p):
201 return _compile, (p.pattern, p.flags)
202
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000203copy_reg.pickle(type(_compile("", 0)), _pickle, _compile)
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000204
205# --------------------------------------------------------------------
206# experimental stuff (see python-dev discussions for details)
207
208class Scanner:
209 def __init__(self, lexicon):
Fredrik Lundh29c4ba92000-08-01 18:20:07 +0000210 from sre_constants import BRANCH, SUBPATTERN
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000211 self.lexicon = lexicon
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000212 # combine phrases into a compound pattern
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000213 p = []
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000214 s = sre_parse.Pattern()
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000215 for phrase, action in lexicon:
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000216 p.append(sre_parse.SubPattern(s, [
Fredrik Lundh29c4ba92000-08-01 18:20:07 +0000217 (SUBPATTERN, (len(p), sre_parse.parse(phrase))),
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000218 ]))
219 p = sre_parse.SubPattern(s, [(BRANCH, (None, p))])
220 s.groups = len(p)
221 self.scanner = sre_compile.compile(p)
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000222 def scan(self, string):
223 result = []
224 append = result.append
225 match = self.scanner.match
226 i = 0
227 while 1:
228 m = match(string, i)
229 if not m:
230 break
231 j = m.end()
232 if i == j:
233 break
Fredrik Lundh019bcb52000-07-02 22:59:57 +0000234 action = self.lexicon[m.lastindex][1]
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000235 if callable(action):
Fredrik Lundh770617b2001-01-14 15:06:11 +0000236 self.match = m
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000237 action = action(self, m.group())
238 if action is not None:
239 append(action)
240 i = j
241 return result, string[i:]