blob: 45333543fb656c606224a68be76d47c5102f232d [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
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +000020# flags
Fredrik Lundh770617b2001-01-14 15:06:11 +000021I = IGNORECASE = sre_compile.SRE_FLAG_IGNORECASE # ignore case
22L = LOCALE = sre_compile.SRE_FLAG_LOCALE # assume current 8-bit locale
23U = UNICODE = sre_compile.SRE_FLAG_UNICODE # assume unicode locale
24M = MULTILINE = sre_compile.SRE_FLAG_MULTILINE # make anchors look for newline
25S = DOTALL = sre_compile.SRE_FLAG_DOTALL # make dot match newline
26X = VERBOSE = sre_compile.SRE_FLAG_VERBOSE # ignore whitespace and comments
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +000027
Fredrik Lundh770617b2001-01-14 15:06:11 +000028# sre extensions (experimental, don't rely on these)
29T = TEMPLATE = sre_compile.SRE_FLAG_TEMPLATE # disable backtracking
30DEBUG = sre_compile.SRE_FLAG_DEBUG # dump pattern after compilation
Fredrik Lundh436c3d582000-06-29 08:58:44 +000031
32# sre exception
Fredrik Lundhbe2211e2000-06-29 16:57:40 +000033error = sre_compile.error
Fredrik Lundh436c3d582000-06-29 08:58:44 +000034
Guido van Rossum7627c0d2000-03-31 14:58:54 +000035# --------------------------------------------------------------------
36# public interface
37
Guido van Rossum7627c0d2000-03-31 14:58:54 +000038def match(pattern, string, flags=0):
Fredrik Lundh770617b2001-01-14 15:06:11 +000039 """Try to apply the pattern at the start of the string, returning
40 a match object, or None if no match was found."""
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +000041 return _compile(pattern, flags).match(string)
Guido van Rossum7627c0d2000-03-31 14:58:54 +000042
43def search(pattern, string, flags=0):
Fredrik Lundh770617b2001-01-14 15:06:11 +000044 """Scan through string looking for a match to the pattern, returning
45 a match object, or None if no match was found."""
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +000046 return _compile(pattern, flags).search(string)
Guido van Rossum7627c0d2000-03-31 14:58:54 +000047
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +000048def sub(pattern, repl, string, count=0):
Fredrik Lundh770617b2001-01-14 15:06:11 +000049 """Return the string obtained by replacing the leftmost
50 non-overlapping occurrences of the pattern in string by the
51 replacement repl"""
Fredrik Lundh7898c3e2000-08-07 20:59:04 +000052 return _compile(pattern, 0).sub(repl, string, count)
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +000053
54def subn(pattern, repl, string, count=0):
Fredrik Lundh770617b2001-01-14 15:06:11 +000055 """Return a 2-tuple containing (new_string, number).
56 new_string is the string obtained by replacing the leftmost
57 non-overlapping occurrences of the pattern in the source
58 string by the replacement repl. number is the number of
59 substitutions that were made."""
Fredrik Lundh7898c3e2000-08-07 20:59:04 +000060 return _compile(pattern, 0).subn(repl, string, count)
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +000061
62def split(pattern, string, maxsplit=0):
Fredrik Lundh770617b2001-01-14 15:06:11 +000063 """Split the source string by the occurrences of the pattern,
64 returning a list containing the resulting substrings."""
Fredrik Lundh7898c3e2000-08-07 20:59:04 +000065 return _compile(pattern, 0).split(string, maxsplit)
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +000066
67def findall(pattern, string, maxsplit=0):
Fredrik Lundh770617b2001-01-14 15:06:11 +000068 """Return a list of all non-overlapping matches in the string.
69
70 If one or more groups are present in the pattern, return a
71 list of groups; this will be a list of tuples if the pattern
72 has more than one group.
73
74 Empty matches are included in the result."""
Fredrik Lundh7898c3e2000-08-07 20:59:04 +000075 return _compile(pattern, 0).findall(string, maxsplit)
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +000076
77def compile(pattern, flags=0):
Fredrik Lundh770617b2001-01-14 15:06:11 +000078 "Compile a regular expression pattern, returning a pattern object."
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +000079 return _compile(pattern, flags)
80
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000081def purge():
Fredrik Lundh770617b2001-01-14 15:06:11 +000082 "Clear the regular expression cache"
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +000083 _cache.clear()
84
Fredrik Lundh436c3d582000-06-29 08:58:44 +000085def template(pattern, flags=0):
Fredrik Lundh770617b2001-01-14 15:06:11 +000086 "Compile a template pattern, returning a pattern object"
87
Fredrik Lundh436c3d582000-06-29 08:58:44 +000088 return _compile(pattern, flags|T)
89
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +000090def escape(pattern):
Fredrik Lundh770617b2001-01-14 15:06:11 +000091 "Escape all non-alphanumeric characters in pattern."
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +000092 s = list(pattern)
93 for i in range(len(pattern)):
94 c = pattern[i]
95 if not ("a" <= c <= "z" or "A" <= c <= "Z" or "0" <= c <= "9"):
96 if c == "\000":
97 s[i] = "\\000"
98 else:
99 s[i] = "\\" + c
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000100 return _join(s, pattern)
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000101
102# --------------------------------------------------------------------
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000103# internals
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000104
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000105_cache = {}
106_MAXCACHE = 100
Guido van Rossum7627c0d2000-03-31 14:58:54 +0000107
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000108def _join(seq, sep):
109 # internal: join into string having the same type as sep
Eric S. Raymondb08b2d32001-02-09 11:10:16 +0000110 return sep[:0].join(seq)
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000111
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000112def _compile(*key):
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000113 # internal: compile pattern
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000114 p = _cache.get(key)
115 if p is not None:
116 return p
117 pattern, flags = key
118 if type(pattern) not in sre_compile.STRING_TYPES:
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000119 return pattern
Fredrik Lundhe1869832000-08-01 22:47:49 +0000120 try:
121 p = sre_compile.compile(pattern, flags)
122 except error, v:
123 raise error, v # invalid expression
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000124 if len(_cache) >= _MAXCACHE:
125 _cache.clear()
126 _cache[key] = p
127 return p
128
Fredrik Lundh5644b7f2000-09-21 17:03:25 +0000129def _expand(pattern, match, template):
130 # internal: match.expand implementation hook
131 template = sre_parse.parse_template(template, pattern)
132 return sre_parse.expand_template(template, match)
133
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000134def _sub(pattern, template, string, count=0):
135 # internal: pattern.sub implementation hook
136 return _subn(pattern, template, string, count)[0]
137
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000138def _subn(pattern, template, string, count=0):
139 # internal: pattern.subn implementation hook
140 if callable(template):
Andrew M. Kuchlinge8d52af2000-06-18 20:27:10 +0000141 filter = template
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000142 else:
Fredrik Lundh90a07912000-06-30 07:50:59 +0000143 template = sre_parse.parse_template(template, pattern)
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000144 def filter(match, template=template):
Fredrik Lundh436c3d582000-06-29 08:58:44 +0000145 return sre_parse.expand_template(template, match)
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000146 n = i = 0
147 s = []
148 append = s.append
Fredrik Lundhbe2211e2000-06-29 16:57:40 +0000149 c = pattern.scanner(string)
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000150 while not count or n < count:
151 m = c.search()
152 if not m:
153 break
Fredrik Lundh90a07912000-06-30 07:50:59 +0000154 b, e = m.span()
Fredrik Lundh01016fe2000-06-30 00:27:46 +0000155 if i < b:
156 append(string[i:b])
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000157 append(filter(m))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000158 i = e
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000159 n = n + 1
Fredrik Lundh01016fe2000-06-30 00:27:46 +0000160 append(string[i:])
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000161 return _join(s, string[:0]), n
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000162
163def _split(pattern, string, maxsplit=0):
164 # internal: pattern.split implementation hook
165 n = i = 0
166 s = []
167 append = s.append
Fredrik Lundhbe2211e2000-06-29 16:57:40 +0000168 extend = s.extend
169 c = pattern.scanner(string)
Fredrik Lundh01016fe2000-06-30 00:27:46 +0000170 g = pattern.groups
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000171 while not maxsplit or n < maxsplit:
172 m = c.search()
173 if not m:
174 break
Fredrik Lundh90a07912000-06-30 07:50:59 +0000175 b, e = m.span()
176 if b == e:
177 if i >= len(string):
178 break
179 continue
Fredrik Lundhbe2211e2000-06-29 16:57:40 +0000180 append(string[i:b])
Fredrik Lundh90a07912000-06-30 07:50:59 +0000181 if g and b != e:
Fredrik Lundh1c5aa692001-01-16 07:37:30 +0000182 extend(list(m.groups()))
Fredrik Lundh90a07912000-06-30 07:50:59 +0000183 i = e
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000184 n = n + 1
Fredrik Lundh80946112000-06-29 18:03:25 +0000185 append(string[i:])
Jeremy Hyltonb1aa1952000-06-01 17:39:12 +0000186 return s
Fredrik Lundh0640e112000-06-30 13:55:15 +0000187
188# register myself for pickling
189
190import copy_reg
191
192def _pickle(p):
193 return _compile, (p.pattern, p.flags)
194
Fredrik Lundh7898c3e2000-08-07 20:59:04 +0000195copy_reg.pickle(type(_compile("", 0)), _pickle, _compile)
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000196
197# --------------------------------------------------------------------
198# experimental stuff (see python-dev discussions for details)
199
200class Scanner:
201 def __init__(self, lexicon):
Fredrik Lundh29c4ba92000-08-01 18:20:07 +0000202 from sre_constants import BRANCH, SUBPATTERN
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000203 self.lexicon = lexicon
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000204 # combine phrases into a compound pattern
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000205 p = []
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000206 s = sre_parse.Pattern()
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000207 for phrase, action in lexicon:
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000208 p.append(sre_parse.SubPattern(s, [
Fredrik Lundh29c4ba92000-08-01 18:20:07 +0000209 (SUBPATTERN, (len(p), sre_parse.parse(phrase))),
Fredrik Lundh8a3ebf82000-07-23 21:46:17 +0000210 ]))
211 p = sre_parse.SubPattern(s, [(BRANCH, (None, p))])
212 s.groups = len(p)
213 self.scanner = sre_compile.compile(p)
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000214 def scan(self, string):
215 result = []
216 append = result.append
217 match = self.scanner.match
218 i = 0
219 while 1:
220 m = match(string, i)
221 if not m:
222 break
223 j = m.end()
224 if i == j:
225 break
Fredrik Lundh019bcb52000-07-02 22:59:57 +0000226 action = self.lexicon[m.lastindex][1]
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000227 if callable(action):
Fredrik Lundh770617b2001-01-14 15:06:11 +0000228 self.match = m
Fredrik Lundh7cafe4d2000-07-02 17:33:27 +0000229 action = action(self, m.group())
230 if action is not None:
231 append(action)
232 i = j
233 return result, string[i:]