• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#
2# Secret Labs' Regular Expression Engine
3#
4# re-compatible interface for the sre matching engine
5#
6# Copyright (c) 1998-2001 by Secret Labs AB.  All rights reserved.
7#
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).
11#
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.
15#
16
17r"""Support for regular expressions (RE).
18
19This module provides regular expression matching operations similar to
20those found in Perl.  It supports both 8-bit and Unicode strings; both
21the pattern and the strings being processed can contain null bytes and
22characters outside the US ASCII range.
23
24Regular expressions can contain both special and ordinary characters.
25Most ordinary characters, like "A", "a", or "0", are the simplest
26regular expressions; they simply match themselves.  You can
27concatenate ordinary characters, so last matches the string 'last'.
28
29The 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    (?aiLmsux) Set the A, 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.
54    (?<=...) Matches if preceded by ... (must be fixed length).
55    (?<!...) Matches if not preceded by ... (must be fixed length).
56    (?(id/name)yes|no) Matches yes pattern if the group with id/name matched,
57                       the (optional) no pattern otherwise.
58
59The special sequences consist of "\\" and a character from the list
60below.  If the ordinary character is not on the list, then the
61resulting RE will match the second character.
62    \number  Matches the contents of the group of the same number.
63    \A       Matches only at the start of the string.
64    \Z       Matches only at the end of the string.
65    \b       Matches the empty string, but only at the start or end of a word.
66    \B       Matches the empty string, but not at the start or end of a word.
67    \d       Matches any decimal digit; equivalent to the set [0-9] in
68             bytes patterns or string patterns with the ASCII flag.
69             In string patterns without the ASCII flag, it will match the whole
70             range of Unicode digits.
71    \D       Matches any non-digit character; equivalent to [^\d].
72    \s       Matches any whitespace character; equivalent to [ \t\n\r\f\v] in
73             bytes patterns or string patterns with the ASCII flag.
74             In string patterns without the ASCII flag, it will match the whole
75             range of Unicode whitespace characters.
76    \S       Matches any non-whitespace character; equivalent to [^\s].
77    \w       Matches any alphanumeric character; equivalent to [a-zA-Z0-9_]
78             in bytes patterns or string patterns with the ASCII flag.
79             In string patterns without the ASCII flag, it will match the
80             range of Unicode alphanumeric characters (letters plus digits
81             plus underscore).
82             With LOCALE, it will match the set [0-9_] plus characters defined
83             as letters for the current locale.
84    \W       Matches the complement of \w.
85    \\       Matches a literal backslash.
86
87This module exports the following functions:
88    match     Match a regular expression pattern to the beginning of a string.
89    fullmatch Match a regular expression pattern to all of a string.
90    search    Search a string for the presence of a pattern.
91    sub       Substitute occurrences of a pattern found in a string.
92    subn      Same as sub, but also return the number of substitutions made.
93    split     Split a string by the occurrences of a pattern.
94    findall   Find all occurrences of a pattern in a string.
95    finditer  Return an iterator yielding a Match object for each match.
96    compile   Compile a pattern into a Pattern object.
97    purge     Clear the regular expression cache.
98    escape    Backslash all non-alphanumerics in a string.
99
100Some of the functions in this module takes flags as optional parameters:
101    A  ASCII       For string patterns, make \w, \W, \b, \B, \d, \D
102                   match the corresponding ASCII character categories
103                   (rather than the whole Unicode categories, which is the
104                   default).
105                   For bytes patterns, this flag is the only available
106                   behaviour and needn't be specified.
107    I  IGNORECASE  Perform case-insensitive matching.
108    L  LOCALE      Make \w, \W, \b, \B, dependent on the current locale.
109    M  MULTILINE   "^" matches the beginning of lines (after a newline)
110                   as well as the string.
111                   "$" matches the end of lines (before a newline) as well
112                   as the end of the string.
113    S  DOTALL      "." matches any character at all, including the newline.
114    X  VERBOSE     Ignore whitespace and comments for nicer looking RE's.
115    U  UNICODE     For compatibility only. Ignored for string patterns (it
116                   is the default), and forbidden for bytes patterns.
117
118This module also defines an exception 'error'.
119
120"""
121
122import enum
123import sre_compile
124import sre_parse
125import functools
126try:
127    import _locale
128except ImportError:
129    _locale = None
130
131
132# public symbols
133__all__ = [
134    "match", "fullmatch", "search", "sub", "subn", "split",
135    "findall", "finditer", "compile", "purge", "template", "escape",
136    "error", "Pattern", "Match", "A", "I", "L", "M", "S", "X", "U",
137    "ASCII", "IGNORECASE", "LOCALE", "MULTILINE", "DOTALL", "VERBOSE",
138    "UNICODE",
139]
140
141__version__ = "2.2.1"
142
143class RegexFlag(enum.IntFlag):
144    ASCII = sre_compile.SRE_FLAG_ASCII # assume ascii "locale"
145    IGNORECASE = sre_compile.SRE_FLAG_IGNORECASE # ignore case
146    LOCALE = sre_compile.SRE_FLAG_LOCALE # assume current 8-bit locale
147    UNICODE = sre_compile.SRE_FLAG_UNICODE # assume unicode "locale"
148    MULTILINE = sre_compile.SRE_FLAG_MULTILINE # make anchors look for newline
149    DOTALL = sre_compile.SRE_FLAG_DOTALL # make dot match newline
150    VERBOSE = sre_compile.SRE_FLAG_VERBOSE # ignore whitespace and comments
151    A = ASCII
152    I = IGNORECASE
153    L = LOCALE
154    U = UNICODE
155    M = MULTILINE
156    S = DOTALL
157    X = VERBOSE
158    # sre extensions (experimental, don't rely on these)
159    TEMPLATE = sre_compile.SRE_FLAG_TEMPLATE # disable backtracking
160    T = TEMPLATE
161    DEBUG = sre_compile.SRE_FLAG_DEBUG # dump pattern after compilation
162globals().update(RegexFlag.__members__)
163
164# sre exception
165error = sre_compile.error
166
167# --------------------------------------------------------------------
168# public interface
169
170def match(pattern, string, flags=0):
171    """Try to apply the pattern at the start of the string, returning
172    a Match object, or None if no match was found."""
173    return _compile(pattern, flags).match(string)
174
175def fullmatch(pattern, string, flags=0):
176    """Try to apply the pattern to all of the string, returning
177    a Match object, or None if no match was found."""
178    return _compile(pattern, flags).fullmatch(string)
179
180def search(pattern, string, flags=0):
181    """Scan through string looking for a match to the pattern, returning
182    a Match object, or None if no match was found."""
183    return _compile(pattern, flags).search(string)
184
185def sub(pattern, repl, string, count=0, flags=0):
186    """Return the string obtained by replacing the leftmost
187    non-overlapping occurrences of the pattern in string by the
188    replacement repl.  repl can be either a string or a callable;
189    if a string, backslash escapes in it are processed.  If it is
190    a callable, it's passed the Match object and must return
191    a replacement string to be used."""
192    return _compile(pattern, flags).sub(repl, string, count)
193
194def subn(pattern, repl, string, count=0, flags=0):
195    """Return a 2-tuple containing (new_string, number).
196    new_string is the string obtained by replacing the leftmost
197    non-overlapping occurrences of the pattern in the source
198    string by the replacement repl.  number is the number of
199    substitutions that were made. repl can be either a string or a
200    callable; if a string, backslash escapes in it are processed.
201    If it is a callable, it's passed the Match object and must
202    return a replacement string to be used."""
203    return _compile(pattern, flags).subn(repl, string, count)
204
205def split(pattern, string, maxsplit=0, flags=0):
206    """Split the source string by the occurrences of the pattern,
207    returning a list containing the resulting substrings.  If
208    capturing parentheses are used in pattern, then the text of all
209    groups in the pattern are also returned as part of the resulting
210    list.  If maxsplit is nonzero, at most maxsplit splits occur,
211    and the remainder of the string is returned as the final element
212    of the list."""
213    return _compile(pattern, flags).split(string, maxsplit)
214
215def findall(pattern, string, flags=0):
216    """Return a list of all non-overlapping matches in the string.
217
218    If one or more capturing groups are present in the pattern, return
219    a list of groups; this will be a list of tuples if the pattern
220    has more than one group.
221
222    Empty matches are included in the result."""
223    return _compile(pattern, flags).findall(string)
224
225def finditer(pattern, string, flags=0):
226    """Return an iterator over all non-overlapping matches in the
227    string.  For each match, the iterator returns a Match object.
228
229    Empty matches are included in the result."""
230    return _compile(pattern, flags).finditer(string)
231
232def compile(pattern, flags=0):
233    "Compile a regular expression pattern, returning a Pattern object."
234    return _compile(pattern, flags)
235
236def purge():
237    "Clear the regular expression caches"
238    _cache.clear()
239    _compile_repl.cache_clear()
240
241def template(pattern, flags=0):
242    "Compile a template pattern, returning a Pattern object"
243    return _compile(pattern, flags|T)
244
245# SPECIAL_CHARS
246# closing ')', '}' and ']'
247# '-' (a range in character set)
248# '&', '~', (extended character set operations)
249# '#' (comment) and WHITESPACE (ignored) in verbose mode
250_special_chars_map = {i: '\\' + chr(i) for i in b'()[]{}?*+-|^$\\.&~# \t\n\r\v\f'}
251
252def escape(pattern):
253    """
254    Escape special characters in a string.
255    """
256    if isinstance(pattern, str):
257        return pattern.translate(_special_chars_map)
258    else:
259        pattern = str(pattern, 'latin1')
260        return pattern.translate(_special_chars_map).encode('latin1')
261
262Pattern = type(sre_compile.compile('', 0))
263Match = type(sre_compile.compile('', 0).match(''))
264
265# --------------------------------------------------------------------
266# internals
267
268_cache = {}  # ordered!
269
270_MAXCACHE = 512
271def _compile(pattern, flags):
272    # internal: compile pattern
273    if isinstance(flags, RegexFlag):
274        flags = flags.value
275    try:
276        return _cache[type(pattern), pattern, flags]
277    except KeyError:
278        pass
279    if isinstance(pattern, Pattern):
280        if flags:
281            raise ValueError(
282                "cannot process flags argument with a compiled pattern")
283        return pattern
284    if not sre_compile.isstring(pattern):
285        raise TypeError("first argument must be string or compiled pattern")
286    p = sre_compile.compile(pattern, flags)
287    if not (flags & DEBUG):
288        if len(_cache) >= _MAXCACHE:
289            # Drop the oldest item
290            try:
291                del _cache[next(iter(_cache))]
292            except (StopIteration, RuntimeError, KeyError):
293                pass
294        _cache[type(pattern), pattern, flags] = p
295    return p
296
297@functools.lru_cache(_MAXCACHE)
298def _compile_repl(repl, pattern):
299    # internal: compile replacement pattern
300    return sre_parse.parse_template(repl, pattern)
301
302def _expand(pattern, match, template):
303    # internal: Match.expand implementation hook
304    template = sre_parse.parse_template(template, pattern)
305    return sre_parse.expand_template(template, match)
306
307def _subx(pattern, template):
308    # internal: Pattern.sub/subn implementation helper
309    template = _compile_repl(template, pattern)
310    if not template[0] and len(template[1]) == 1:
311        # literal replacement
312        return template[1][0]
313    def filter(match, template=template):
314        return sre_parse.expand_template(template, match)
315    return filter
316
317# register myself for pickling
318
319import copyreg
320
321def _pickle(p):
322    return _compile, (p.pattern, p.flags)
323
324copyreg.pickle(Pattern, _pickle, _compile)
325
326# --------------------------------------------------------------------
327# experimental stuff (see python-dev discussions for details)
328
329class Scanner:
330    def __init__(self, lexicon, flags=0):
331        from sre_constants import BRANCH, SUBPATTERN
332        if isinstance(flags, RegexFlag):
333            flags = flags.value
334        self.lexicon = lexicon
335        # combine phrases into a compound pattern
336        p = []
337        s = sre_parse.Pattern()
338        s.flags = flags
339        for phrase, action in lexicon:
340            gid = s.opengroup()
341            p.append(sre_parse.SubPattern(s, [
342                (SUBPATTERN, (gid, 0, 0, sre_parse.parse(phrase, flags))),
343                ]))
344            s.closegroup(gid, p[-1])
345        p = sre_parse.SubPattern(s, [(BRANCH, (None, p))])
346        self.scanner = sre_compile.compile(p)
347    def scan(self, string):
348        result = []
349        append = result.append
350        match = self.scanner.scanner(string).match
351        i = 0
352        while True:
353            m = match()
354            if not m:
355                break
356            j = m.end()
357            if i == j:
358                break
359            action = self.lexicon[m.lastindex-1][1]
360            if callable(action):
361                self.match = m
362                action = action(self, m.group())
363            if action is not None:
364                append(action)
365            i = j
366        return result, string[i:]
367