2 # Secret Labs' Regular Expression Engine
4 # re-compatible interface for the sre matching engine
6 # Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved.
8 # 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).
12 # Portions of this engine have been developed in cooperation with
13 # CNRI. Hewlett-Packard provided funding for 1.6 integration and
14 # other compatibility work.
17 r
"""Support for regular expressions (RE).
19 This module provides regular expression matching operations similar to
20 those found in Perl. It supports both 8-bit and Unicode strings; both
21 the pattern and the strings being processed can contain null bytes and
22 characters outside the US ASCII range.
24 Regular expressions can contain both special and ordinary characters.
25 Most ordinary characters, like "A", "a", or "0", are the simplest
26 regular expressions; they simply match themselves. You can
27 concatenate ordinary characters, so last matches the string 'last'.
29 The special characters are:
30 "." Matches any character except a newline.
31 "^" Matches the start of the string.
32 "$" Matches the end of the string or just before the newline at
33 the end of the string.
34 "*" Matches 0 or more (greedy) repetitions of the preceding RE.
35 Greedy means that it will match as many repetitions as possible.
36 "+" Matches 1 or more (greedy) repetitions of the preceding RE.
37 "?" Matches 0 or 1 (greedy) of the preceding RE.
38 *?,+?,?? Non-greedy versions of the previous three special characters.
39 {m,n} Matches from m to n repetitions of the preceding RE.
40 {m,n}? Non-greedy version of the above.
41 "\\" Either escapes special characters or signals a special sequence.
42 [] Indicates a set of characters.
43 A "^" as the first character indicates a complementing set.
44 "|" A|B, creates an RE that will match either A or B.
45 (...) Matches the RE inside the parentheses.
46 The contents can be retrieved or matched later in the string.
47 (?iLmsux) Set the I, L, M, S, U, or X flag for the RE (see below).
48 (?:...) Non-grouping version of regular parentheses.
49 (?P<name>...) The substring matched by the group is accessible by name.
50 (?P=name) Matches the text matched earlier by the group named name.
51 (?#...) A comment; ignored.
52 (?=...) Matches if ... matches next, but doesn't consume the string.
53 (?!...) Matches if ... doesn't match next.
55 The special sequences consist of "\\" and a character from the list
56 below. If the ordinary character is not on the list, then the
57 resulting RE will match the second character.
58 \number Matches the contents of the group of the same number.
59 \A Matches only at the start of the string.
60 \Z Matches only at the end of the string.
61 \b Matches the empty string, but only at the start or end of a word.
62 \B Matches the empty string, but not at the start or end of a word.
63 \d Matches any decimal digit; equivalent to the set [0-9].
64 \D Matches any non-digit character; equivalent to the set [^0-9].
65 \s Matches any whitespace character; equivalent to [ \t\n\r\f\v].
66 \S Matches any non-whitespace character; equiv. to [^ \t\n\r\f\v].
67 \w Matches any alphanumeric character; equivalent to [a-zA-Z0-9_].
68 With LOCALE, it will match the set [0-9_] plus characters defined
69 as letters for the current locale.
70 \W Matches the complement of \w.
71 \\ Matches a literal backslash.
73 This module exports the following functions:
74 match Match a regular expression pattern to the beginning of a string.
75 search Search a string for the presence of a pattern.
76 sub Substitute occurrences of a pattern found in a string.
77 subn Same as sub, but also return the number of substitutions made.
78 split Split a string by the occurrences of a pattern.
79 findall Find all occurrences of a pattern in a string.
80 compile Compile a pattern into a RegexObject.
81 purge Clear the regular expression cache.
82 escape Backslash all non-alphanumerics in a string.
84 Some of the functions in this module takes flags as optional parameters:
85 I IGNORECASE Perform case-insensitive matching.
86 L LOCALE Make \w, \W, \b, \B, dependent on the current locale.
87 M MULTILINE "^" matches the beginning of lines (after a newline)
88 as well as the string.
89 "$" matches the end of lines (before a newline) as well
90 as the end of 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 Make \w, \W, \b, \B, dependent on the Unicode locale.
95 This module also defines an exception 'error'.
104 __all__
= [ "match", "search", "sub", "subn", "split", "findall",
105 "compile", "purge", "template", "escape", "I", "L", "M", "S", "X",
106 "U", "IGNORECASE", "LOCALE", "MULTILINE", "DOTALL", "VERBOSE",
109 __version__
= "2.2.1"
112 I
= IGNORECASE
= sre_compile
.SRE_FLAG_IGNORECASE
# ignore case
113 L
= LOCALE
= sre_compile
.SRE_FLAG_LOCALE
# assume current 8-bit locale
114 U
= UNICODE
= sre_compile
.SRE_FLAG_UNICODE
# assume unicode locale
115 M
= MULTILINE
= sre_compile
.SRE_FLAG_MULTILINE
# make anchors look for newline
116 S
= DOTALL
= sre_compile
.SRE_FLAG_DOTALL
# make dot match newline
117 X
= VERBOSE
= sre_compile
.SRE_FLAG_VERBOSE
# ignore whitespace and comments
119 # sre extensions (experimental, don't rely on these)
120 T
= TEMPLATE
= sre_compile
.SRE_FLAG_TEMPLATE
# disable backtracking
121 DEBUG
= sre_compile
.SRE_FLAG_DEBUG
# dump pattern after compilation
124 error
= sre_compile
.error
126 # --------------------------------------------------------------------
129 def match(pattern
, string
, flags
=0):
130 """Try to apply the pattern at the start of the string, returning
131 a match object, or None if no match was found."""
132 return _compile(pattern
, flags
).match(string
)
134 def search(pattern
, string
, flags
=0):
135 """Scan through string looking for a match to the pattern, returning
136 a match object, or None if no match was found."""
137 return _compile(pattern
, flags
).search(string
)
139 def sub(pattern
, repl
, string
, count
=0):
140 """Return the string obtained by replacing the leftmost
141 non-overlapping occurrences of the pattern in string by the
142 replacement repl. repl can be either a string or a callable;
143 if a callable, it's passed the match object and must return
144 a replacement string to be used."""
145 return _compile(pattern
, 0).sub(repl
, string
, count
)
147 def subn(pattern
, repl
, string
, count
=0):
148 """Return a 2-tuple containing (new_string, number).
149 new_string is the string obtained by replacing the leftmost
150 non-overlapping occurrences of the pattern in the source
151 string by the replacement repl. number is the number of
152 substitutions that were made. repl can be either a string or a
153 callable; if a callable, it's passed the match object and must
154 return a replacement string to be used."""
155 return _compile(pattern
, 0).subn(repl
, string
, count
)
157 def split(pattern
, string
, maxsplit
=0):
158 """Split the source string by the occurrences of the pattern,
159 returning a list containing the resulting substrings."""
160 return _compile(pattern
, 0).split(string
, maxsplit
)
162 def findall(pattern
, string
, flags
=0):
163 """Return a list of all non-overlapping matches in the string.
165 If one or more groups are present in the pattern, return a
166 list of groups; this will be a list of tuples if the pattern
167 has more than one group.
169 Empty matches are included in the result."""
170 return _compile(pattern
, flags
).findall(string
)
172 if sys
.hexversion
>= 0x02020000:
173 __all__
.append("finditer")
174 def finditer(pattern
, string
, flags
=0):
175 """Return an iterator over all non-overlapping matches in the
176 string. For each match, the iterator returns a match object.
178 Empty matches are included in the result."""
179 return _compile(pattern
, flags
).finditer(string
)
181 def compile(pattern
, flags
=0):
182 "Compile a regular expression pattern, returning a pattern object."
183 return _compile(pattern
, flags
)
186 "Clear the regular expression cache"
190 def template(pattern
, flags
=0):
191 "Compile a template pattern, returning a pattern object"
192 return _compile(pattern
, flags|T
)
195 for c
in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890':
200 "Escape all non-alphanumeric characters in pattern."
203 for i
in range(len(pattern
)):
205 if c
not in alphanum
:
210 return pattern
[:0].join(s
)
212 # --------------------------------------------------------------------
218 _pattern_type
= type(sre_compile
.compile("", 0))
223 # internal: compile pattern
224 cachekey
= (type(key
[0]),) + key
225 p
= _cache
.get(cachekey
)
229 if isinstance(pattern
, _pattern_type
):
231 raise ValueError('Cannot process flags argument with a compiled pattern')
233 if not sre_compile
.isstring(pattern
):
234 raise TypeError, "first argument must be string or compiled pattern"
236 p
= sre_compile
.compile(pattern
, flags
)
238 raise error
, v
# invalid expression
239 if len(_cache
) >= _MAXCACHE
:
244 def _compile_repl(*key
):
245 # internal: compile replacement pattern
246 p
= _cache_repl
.get(key
)
251 p
= sre_parse
.parse_template(repl
, pattern
)
253 raise error
, v
# invalid expression
254 if len(_cache_repl
) >= _MAXCACHE
:
259 def _expand(pattern
, match
, template
):
260 # internal: match.expand implementation hook
261 template
= sre_parse
.parse_template(template
, pattern
)
262 return sre_parse
.expand_template(template
, match
)
264 def _subx(pattern
, template
):
265 # internal: pattern.sub/subn implementation helper
266 template
= _compile_repl(template
, pattern
)
267 if not template
[0] and len(template
[1]) == 1:
268 # literal replacement
269 return template
[1][0]
270 def filter(match
, template
=template
):
271 return sre_parse
.expand_template(template
, match
)
274 # register myself for pickling
279 return _compile
, (p
.pattern
, p
.flags
)
281 copy_reg
.pickle(_pattern_type
, _pickle
, _compile
)
283 # --------------------------------------------------------------------
284 # experimental stuff (see python-dev discussions for details)
287 def __init__(self
, lexicon
, flags
=0):
288 from sre_constants
import BRANCH
, SUBPATTERN
289 self
.lexicon
= lexicon
290 # combine phrases into a compound pattern
292 s
= sre_parse
.Pattern()
294 for phrase
, action
in lexicon
:
295 p
.append(sre_parse
.SubPattern(s
, [
296 (SUBPATTERN
, (len(p
)+1, sre_parse
.parse(phrase
, flags
))),
298 p
= sre_parse
.SubPattern(s
, [(BRANCH
, (None, p
))])
300 self
.scanner
= sre_compile
.compile(p
)
301 def scan(self
, string
):
303 append
= result
.append
304 match
= self
.scanner
.scanner(string
).match
313 action
= self
.lexicon
[m
.lastindex
-1][1]
316 action
= action(self
, m
.group())
317 if action
is not None:
320 return result
, string
[i
:]