blob: 859ff9e70ddea99e8c79a8332a133aecc57b2cab [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 Lundh436c3d582000-06-29 08:58:44 +000018import sre_parse
Guido van Rossum7627c0d2000-03-31 14:58:54 +000019
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000020import string
21
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +000022# flags
Fredrik Lundh770617b2001-01-14 15:06:11 +000023I = IGNORECASE = sre_compile.SRE_FLAG_IGNORECASE # ignore case
24L = LOCALE = sre_compile.SRE_FLAG_LOCALE # assume current 8-bit locale
25U = UNICODE = sre_compile.SRE_FLAG_UNICODE # assume unicode locale
26M = MULTILINE = sre_compile.SRE_FLAG_MULTILINE # make anchors look for newline
27S = DOTALL = sre_compile.SRE_FLAG_DOTALL # make dot match newline
28X = VERBOSE = sre_compile.SRE_FLAG_VERBOSE # ignore whitespace and comments
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +000029
Fredrik Lundh770617b2001-01-14 15:06:11 +000030# sre extensions (experimental, don't rely on these)
31T = TEMPLATE = sre_compile.SRE_FLAG_TEMPLATE # disable backtracking
32DEBUG = sre_compile.SRE_FLAG_DEBUG # dump pattern after compilation
Fredrik Lundh436c3d582000-06-29 08:58:44 +000033
34# sre exception
Fredrik Lundhbe2211e2000-06-29 16:57:40 +000035error = sre_compile.error
Fredrik Lundh436c3d582000-06-29 08:58:44 +000036
Guido van Rossum7627c0d2000-03-31 14:58:54 +000037# --------------------------------------------------------------------
38# public interface
39
Guido van Rossum7627c0d2000-03-31 14:58:54 +000040def match(pattern, string, flags=0):
Fredrik Lundh770617b2001-01-14 15:06:11 +000041 """Try to apply the pattern at the start of the string, returning
42 a match object, or None if no match was found."""
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +000043 return _compile(pattern, flags).match(string)
Guido van Rossum7627c0d2000-03-31 14:58:54 +000044
45def search(pattern, string, flags=0):
Fredrik Lundh770617b2001-01-14 15:06:11 +000046 """Scan through string looking for a match to the pattern, returning
47 a match object, or None if no match was found."""
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +000048 return _compile(pattern, flags).search(string)
Guido van Rossum7627c0d2000-03-31 14:58:54 +000049
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +000050def sub(pattern, repl, string, count=0):
Fredrik Lundh770617b2001-01-14 15:06:11 +000051 """Return the string obtained by replacing the leftmost
52 non-overlapping occurrences of the pattern in string by the
53 replacement repl"""
Fredrik Lundh7898c3e2000-08-07 20:59:04 +000054 return _compile(pattern, 0).sub(repl, string, count)
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +000055
56def subn(pattern, repl, string, count=0):
Fredrik Lundh770617b2001-01-14 15:06:11 +000057 """Return a 2-tuple containing (new_string, number).
58 new_string is the string obtained by replacing the leftmost
59 non-overlapping occurrences of the pattern in the source
60 string by the replacement repl. number is the number of
61 substitutions that were made."""
Fredrik Lundh7898c3e2000-08-07 20:59:04 +000062 return _compile(pattern, 0).subn(repl, string, count)
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +000063
64def split(pattern, string, maxsplit=0):
Fredrik Lundh770617b2001-01-14 15:06:11 +000065 """Split the source string by the occurrences of the pattern,
66 returning a list containing the resulting substrings."""
Fredrik Lundh7898c3e2000-08-07 20:59:04 +000067 return _compile(pattern, 0).split(string, maxsplit)
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +000068
69def findall(pattern, string, maxsplit=0):
Fredrik Lundh770617b2001-01-14 15:06:11 +000070 """Return a list of all non-overlapping matches in the string.
71
72 If one or more groups are present in the pattern, return a
73 list of groups; this will be a list of tuples if the pattern
74 has more than one group.
75
76 Empty matches are included in the result."""
Fredrik Lundh7898c3e2000-08-07 20:59:04 +000077 return _compile(pattern, 0).findall(string, maxsplit)
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +000078
79def compile(pattern, flags=0):
Fredrik Lundh770617b2001-01-14 15:06:11 +000080 "Compile a regular expression pattern, returning a pattern object."
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +000081 return _compile(pattern, flags)
82
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000083def purge():
Fredrik Lundh770617b2001-01-14 15:06:11 +000084 "Clear the regular expression cache"
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000085 _cache.clear()
86
Fredrik Lundh436c3d582000-06-29 08:58:44 +000087def template(pattern, flags=0):
Fredrik Lundh770617b2001-01-14 15:06:11 +000088 "Compile a template pattern, returning a pattern object"
89
Fredrik Lundh436c3d582000-06-29 08:58:44 +000090 return _compile(pattern, flags|T)
91
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +000092def escape(pattern):
Fredrik Lundh770617b2001-01-14 15:06:11 +000093 "Escape all non-alphanumeric characters in pattern."
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +000094 s = list(pattern)
95 for i in range(len(pattern)):
96 c = pattern[i]
97 if not ("a" <= c <= "z" or "A" <= c <= "Z" or "0" <= c <= "9"):
98 if c == "\000":
99 s[i] = "\\000"
100 else:
101 s[i] = "\\" + c
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000102 return _join(s, pattern)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000103
104# --------------------------------------------------------------------
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000105# internals
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000106
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000107_cache = {}
108_MAXCACHE = 100
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000109
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000110def _join(seq, sep):
111 # internal: join into string having the same type as sep
112 return string.join(seq, sep[:0])
113
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000114def _compile(*key):
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000115 # internal: compile pattern
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000116 p = _cache.get(key)
117 if p is not None:
118 return p
119 pattern, flags = key
120 if type(pattern) not in sre_compile.STRING_TYPES:
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000121 return pattern
Fredrik Lundhe1869832000-08-01 22:47:49 +0000122 try:
123 p = sre_compile.compile(pattern, flags)
124 except error, v:
125 raise error, v # invalid expression
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000126 if len(_cache) >= _MAXCACHE:
127 _cache.clear()
128 _cache[key] = p
129 return p
130
Fredrik Lundh5644b7f2000-09-21 17:03:25 +0000131def _expand(pattern, match, template):
132 # internal: match.expand implementation hook
133 template = sre_parse.parse_template(template, pattern)
134 return sre_parse.expand_template(template, match)
135
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000136def _sub(pattern, template, string, count=0):
137 # internal: pattern.sub implementation hook
138 return _subn(pattern, template, string, count)[0]
139
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000140def _subn(pattern, template, string, count=0):
141 # internal: pattern.subn implementation hook
142 if callable(template):
Andrew M. Kuchlinge8d52af2000-06-18 20:27:10 +0000143 filter = template
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000144 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000145 template = sre_parse.parse_template(template, pattern)
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000146 def filter(match, template=template):
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000147 return sre_parse.expand_template(template, match)
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000148 n = i = 0
149 s = []
150 append = s.append
Fredrik Lundhbe2211e2000-06-29 16:57:40 +0000151 c = pattern.scanner(string)
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000152 while not count or n < count:
153 m = c.search()
154 if not m:
155 break
Fredrik Lundh90a07912000-06-30 07:50:59 +0000156 b, e = m.span()
Fredrik Lundh01016fe2000-06-30 00:27:46 +0000157 if i < b:
158 append(string[i:b])
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000159 append(filter(m))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000160 i = e
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000161 n = n + 1
Fredrik Lundh01016fe2000-06-30 00:27:46 +0000162 append(string[i:])
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000163 return _join(s, string[:0]), n
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000164
165def _split(pattern, string, maxsplit=0):
166 # internal: pattern.split implementation hook
167 n = i = 0
168 s = []
169 append = s.append
Fredrik Lundhbe2211e2000-06-29 16:57:40 +0000170 extend = s.extend
171 c = pattern.scanner(string)
Fredrik Lundh01016fe2000-06-30 00:27:46 +0000172 g = pattern.groups
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000173 while not maxsplit or n < maxsplit:
174 m = c.search()
175 if not m:
176 break
Fredrik Lundh90a07912000-06-30 07:50:59 +0000177 b, e = m.span()
178 if b == e:
179 if i >= len(string):
180 break
181 continue
Fredrik Lundhbe2211e2000-06-29 16:57:40 +0000182 append(string[i:b])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000183 if g and b != e:
Fredrik Lundh1c5aa692001-01-16 07:37:30 +0000184 extend(list(m.groups()))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000185 i = e
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000186 n = n + 1
Fredrik Lundh80946112000-06-29 18:03:25 +0000187 append(string[i:])
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000188 return s
Fredrik Lundh0640e112000-06-30 13:55:15 +0000189
190# register myself for pickling
191
192import copy_reg
193
194def _pickle(p):
195 return _compile, (p.pattern, p.flags)
196
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000197copy_reg.pickle(type(_compile("", 0)), _pickle, _compile)
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000198
199# --------------------------------------------------------------------
200# experimental stuff (see python-dev discussions for details)
201
202class Scanner:
203 def __init__(self, lexicon):
Fredrik Lundh29c4ba92000-08-01 18:20:07 +0000204 from sre_constants import BRANCH, SUBPATTERN
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000205 self.lexicon = lexicon
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000206 # combine phrases into a compound pattern
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000207 p = []
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000208 s = sre_parse.Pattern()
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000209 for phrase, action in lexicon:
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000210 p.append(sre_parse.SubPattern(s, [
Fredrik Lundh29c4ba92000-08-01 18:20:07 +0000211 (SUBPATTERN, (len(p), sre_parse.parse(phrase))),
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000212 ]))
213 p = sre_parse.SubPattern(s, [(BRANCH, (None, p))])
214 s.groups = len(p)
215 self.scanner = sre_compile.compile(p)
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000216 def scan(self, string):
217 result = []
218 append = result.append
219 match = self.scanner.match
220 i = 0
221 while 1:
222 m = match(string, i)
223 if not m:
224 break
225 j = m.end()
226 if i == j:
227 break
Fredrik Lundh019bcb52000-07-02 22:59:57 +0000228 action = self.lexicon[m.lastindex][1]
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000229 if callable(action):
Fredrik Lundh770617b2001-01-14 15:06:11 +0000230 self.match = m
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000231 action = action(self, m.group())
232 if action is not None:
233 append(action)
234 i = j
235 return result, string[i:]