Hàm re.sub trong python

This module provides regular expression matching operations similar to those found in Perl. Both patterns and strings to be searched can be Unicode strings as well as 8-bit strings.

Regular expressions use the backslash character (

result = re.match(pattern, string)
4) to indicate special forms or to allow special characters to be used without invoking their special meaning. This collides with Python’s usage of the same character for the same purpose in string literals; for example, to match a literal backslash, one might have to write
result = re.match(pattern, string)
5 as the pattern string, because the regular expression must be
result = re.match(pattern, string)
6, and each backslash must be expressed as
result = re.match(pattern, string)
6 inside a regular Python string literal.

The solution is to use Python’s raw string notation for regular expression patterns; backslashes are not handled in any special way in a string literal prefixed with

result = re.match(pattern, string)
8. So
result = re.match(pattern, string)
9 is a two-character string containing
result = re.match(pattern, string)
4 and
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
1, while
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
2 is a one-character string containing a newline. Usually patterns will be expressed in Python code using this raw string notation.

It is important to note that most regular expression operations are available as module-level functions and methods. The functions are shortcuts that don’t require you to compile a regex object first, but miss some fine-tuning parameters.

See also

The third-party regex module, which has an API compatible with the standard library module, but offers additional functionality and a more thorough Unicode support.

7.2.1. Regular Expression Syntax

A regular expression (or RE) specifies a set of strings that matches it; the functions in this module let you check if a particular string matches a given regular expression (or if a given regular expression matches a particular string, which comes down to the same thing).

Regular expressions can be concatenated to form new regular expressions; if A and B are both regular expressions, then AB is also a regular expression. In general, if a string p matches A and another string q matches B, the string pq will match AB. This holds unless A or B contain low precedence operations; boundary conditions between A and B; or have numbered group references. Thus, complex expressions can easily be constructed from simpler primitive expressions like the ones described here. For details of the theory and implementation of regular expressions, consult the Friedl book referenced above, or almost any textbook about compiler construction.

A brief explanation of the format of regular expressions follows. For further information and a gentler presentation, consult the .

Regular expressions can contain both special and ordinary characters. Most ordinary characters, like

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
5,
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
6, or
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
7, are the simplest regular expressions; they simply match themselves. You can concatenate ordinary characters, so
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
8 matches the string
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
9. (In the rest of this section, we’ll write RE’s in
>>> re.split('\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split('\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
0, usually without quotes, and strings to be matched
>>> re.split('\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split('\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
1.)

Some characters, like

>>> re.split('\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split('\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
2 or
>>> re.split('\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split('\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
3, are special. Special characters either stand for classes of ordinary characters, or affect how the regular expressions around them are interpreted. Regular expression pattern strings may not contain null bytes, but can specify the null byte using the
>>> re.split('\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split('\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
4 notation, e.g.,
>>> re.split('\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split('\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
5.

Repetition qualifiers (

>>> re.split('\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split('\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
6,
>>> re.split('\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split('\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
7,
>>> re.split('\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split('\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
8,
>>> re.split('\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split('\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
9, etc) cannot be directly nested. This avoids ambiguity with the non-greedy modifier suffix
>>> re.split('\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split('\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
8, and with other modifiers in other implementations. To apply a second repetition to an inner repetition, parentheses may be used. For example, the expression
>>> re.split('(\W+)', '...words, words...')
['', '...', 'words', ', ', 'words', '...', '']
1 matches any multiple of six
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
6 characters.

The special characters are:

>>> re.split('(\W+)', '...words, words...')
['', '...', 'words', ', ', 'words', '...', '']
3

(Dot.) In the default mode, this matches any character except a newline. If the flag has been specified, this matches any character including a newline.

>>> re.split('(\W+)', '...words, words...')
['', '...', 'words', ', ', 'words', '...', '']
5

(Caret.) Matches the start of the string, and in mode also matches immediately after each newline.

>>> re.split('(\W+)', '...words, words...')
['', '...', 'words', ', ', 'words', '...', '']
7

Matches the end of the string or just before the newline at the end of the string, and in mode also matches before a newline.

>>> re.split('(\W+)', '...words, words...')
['', '...', 'words', ', ', 'words', '...', '']
9 matches both ‘foo’ and ‘foobar’, while the regular expression
>>> re.split('x*', 'foo')
['foo']
>>> re.split("(?m)^$", "foo\n\nbar\n")
['foo\n\nbar\n']
0 matches only ‘foo’. More interestingly, searching for
>>> re.split('x*', 'foo')
['foo']
>>> re.split("(?m)^$", "foo\n\nbar\n")
['foo\n\nbar\n']
1 in
>>> re.split('x*', 'foo')
['foo']
>>> re.split("(?m)^$", "foo\n\nbar\n")
['foo\n\nbar\n']
2 matches ‘foo2’ normally, but ‘foo1’ in mode; searching for a single
>>> re.split('x*', 'foo')
['foo']
>>> re.split("(?m)^$", "foo\n\nbar\n")
['foo\n\nbar\n']
4 in
>>> re.split('x*', 'foo')
['foo']
>>> re.split("(?m)^$", "foo\n\nbar\n")
['foo\n\nbar\n']
5 will find two (empty) matches: one just before the newline, and one at the end of the string.

>>> re.split('x*', 'foo')
['foo']
>>> re.split("(?m)^$", "foo\n\nbar\n")
['foo\n\nbar\n']
6

Causes the resulting RE to match 0 or more repetitions of the preceding RE, as many repetitions as are possible.

>>> re.split('x*', 'foo')
['foo']
>>> re.split("(?m)^$", "foo\n\nbar\n")
['foo\n\nbar\n']
7 will match ‘a’, ‘ab’, or ‘a’ followed by any number of ‘b’s.

>>> re.split('x*', 'foo')
['foo']
>>> re.split("(?m)^$", "foo\n\nbar\n")
['foo\n\nbar\n']
8

Causes the resulting RE to match 1 or more repetitions of the preceding RE.

>>> re.split('x*', 'foo')
['foo']
>>> re.split("(?m)^$", "foo\n\nbar\n")
['foo\n\nbar\n']
9 will match ‘a’ followed by any non-zero number of ‘b’s; it will not match just ‘a’.

>>> re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',
...        r'static PyObject*\npy_\1(void)\n{',
...        'def myfunc():')
'static PyObject*\npy_myfunc(void)\n{'
0

Causes the resulting RE to match 0 or 1 repetitions of the preceding RE.

>>> re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',
...        r'static PyObject*\npy_\1(void)\n{',
...        'def myfunc():')
'static PyObject*\npy_myfunc(void)\n{'
1 will match either ‘a’ or ‘ab’.

>>> re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',
...        r'static PyObject*\npy_\1(void)\n{',
...        'def myfunc():')
'static PyObject*\npy_myfunc(void)\n{'
2,
>>> re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',
...        r'static PyObject*\npy_\1(void)\n{',
...        'def myfunc():')
'static PyObject*\npy_myfunc(void)\n{'
3,
>>> re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',
...        r'static PyObject*\npy_\1(void)\n{',
...        'def myfunc():')
'static PyObject*\npy_myfunc(void)\n{'
4

The

>>> re.split('x*', 'foo')
['foo']
>>> re.split("(?m)^$", "foo\n\nbar\n")
['foo\n\nbar\n']
6,
>>> re.split('x*', 'foo')
['foo']
>>> re.split("(?m)^$", "foo\n\nbar\n")
['foo\n\nbar\n']
8, and
>>> re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',
...        r'static PyObject*\npy_\1(void)\n{',
...        'def myfunc():')
'static PyObject*\npy_myfunc(void)\n{'
0 qualifiers are all greedy; they match as much text as possible. Sometimes this behaviour isn’t desired; if the RE
>>> re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',
...        r'static PyObject*\npy_\1(void)\n{',
...        'def myfunc():')
'static PyObject*\npy_myfunc(void)\n{'
8 is matched against
>>> re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',
...        r'static PyObject*\npy_\1(void)\n{',
...        'def myfunc():')
'static PyObject*\npy_myfunc(void)\n{'
9, it will match the entire string, and not just
>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
00. Adding
>>> re.split('\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split('\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
8 after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. Using the RE
>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
02 will match only
>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
00.

>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
04

Specifies that exactly m copies of the previous RE should be matched; fewer matches cause the entire RE not to match. For example,

>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
05 will match exactly six
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
6 characters, but not five.

>>> re.split('\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split('\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
9

Causes the resulting RE to match from m to n repetitions of the preceding RE, attempting to match as many repetitions as possible. For example,

>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
08 will match from 3 to 5
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
6 characters. Omitting m specifies a lower bound of zero, and omitting n specifies an infinite upper bound. As an example,
>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
10 will match
>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
11 or a thousand
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
6 characters followed by a
>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
13, but not
>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
14. The comma may not be omitted or the modifier would be confused with the previously described form.

>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
15

Causes the resulting RE to match from m to n repetitions of the preceding RE, attempting to match as few repetitions as possible. This is the non-greedy version of the previous qualifier. For example, on the 6-character string

>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
16,
>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
08 will match 5
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
6 characters, while
>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
19 will only match 3 characters.

result = re.match(pattern, string)
4

Either escapes special characters (permitting you to match characters like

>>> re.split('x*', 'foo')
['foo']
>>> re.split("(?m)^$", "foo\n\nbar\n")
['foo\n\nbar\n']
6,
>>> re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',
...        r'static PyObject*\npy_\1(void)\n{',
...        'def myfunc():')
'static PyObject*\npy_myfunc(void)\n{'
0, and so forth), or signals a special sequence; special sequences are discussed below.

If you’re not using a raw string to express the pattern, remember that Python also uses the backslash as an escape sequence in string literals; if the escape sequence isn’t recognized by Python’s parser, the backslash and subsequent character are included in the resulting string. However, if Python would recognize the resulting sequence, the backslash should be repeated twice. This is complicated and hard to understand, so it’s highly recommended that you use raw strings for all but the simplest expressions.

>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
23

Used to indicate a set of characters. In a set:

  • Characters can be listed individually, e.g.

    >>> m = re.search('(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    24 will match
    a = re.compile(r"""\d +  # the integral part
                       \.    # the decimal point
                       \d *  # some fractional digits""", re.X)
    b = re.compile(r"\d+\.\d*")
    
    6,
    >>> m = re.search('(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    26, or
    >>> m = re.search('(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    27.

  • Ranges of characters can be indicated by giving two characters and separating them by a

    >>> m = re.search('(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    28, for example
    >>> m = re.search('(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    29 will match any lowercase ASCII letter,
    >>> m = re.search('(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    30 will match all the two-digits numbers from
    >>> m = re.search('(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    31 to
    >>> m = re.search('(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    32, and
    >>> m = re.search('(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    33 will match any hexadecimal digit. If
    >>> m = re.search('(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    34 is escaped (e.g.
    >>> m = re.search('(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    35) or if it’s placed as the first or last character (e.g.
    >>> m = re.search('(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    36), it will match a literal
    >>> m = re.search('(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    28.

  • Special characters lose their special meaning inside sets. For example,

    >>> m = re.search('(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    38 will match any of the literal characters
    >>> re.split('\W+', 'Words, words, words.')
    ['Words', 'words', 'words', '']
    >>> re.split('(\W+)', 'Words, words, words.')
    ['Words', ', ', 'words', ', ', 'words', '.', '']
    >>> re.split('\W+', 'Words, words, words.', 1)
    ['Words', 'words, words.']
    >>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
    ['0', '3', '9']
    
    3,
    >>> re.split('x*', 'foo')
    ['foo']
    >>> re.split("(?m)^$", "foo\n\nbar\n")
    ['foo\n\nbar\n']
    
    8,
    >>> re.split('x*', 'foo')
    ['foo']
    >>> re.split("(?m)^$", "foo\n\nbar\n")
    ['foo\n\nbar\n']
    
    6, or
    >>> m = re.search('(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    42.

  • Character classes such as

    >>> m = re.search('(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    43 or
    >>> m = re.search('(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    44 (defined below) are also accepted inside a set, although the characters they match depends on whether or mode is in force.

  • Characters that are not within a range can be matched by complementing the set. If the first character of the set is

    >>> re.split('(\W+)', '...words, words...')
    ['', '...', 'words', ', ', 'words', '...', '']
    
    5, all the characters that are not in the set will be matched. For example,
    >>> m = re.search('(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    48 will match any character except
    >>> m = re.search('(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    49, and
    >>> m = re.search('(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    50 will match any character except
    >>> re.split('(\W+)', '...words, words...')
    ['', '...', 'words', ', ', 'words', '...', '']
    
    5.
    >>> m = re.search('(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    52 has no special meaning if it’s not the first character in the set.

  • To match a literal

    >>> m = re.search('(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    53 inside a set, precede it with a backslash, or place it at the beginning of the set. For example, both
    >>> m = re.search('(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    54 and
    >>> m = re.search('(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    55 will both match a parenthesis.

>>> re.split('\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split('\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
2

>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
57, where A and B can be arbitrary REs, creates a regular expression that will match either A or B. An arbitrary number of REs can be separated by the
>>> re.split('\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split('\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
2 in this way. This can be used inside groups (see below) as well. As the target string is scanned, REs separated by
>>> re.split('\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split('\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
2 are tried from left to right. When one pattern completely matches, that branch is accepted. This means that once
>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
60 matches,
>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
61 will not be tested further, even if it would produce a longer overall match. In other words, the
>>> re.split('\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split('\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
2 operator is never greedy. To match a literal
>>> re.split('\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split('\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
2, use
>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
64, or enclose it inside a character class, as in
>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
65.

>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
66

Matches whatever regular expression is inside the parentheses, and indicates the start and end of a group; the contents of a group can be retrieved after a match has been performed, and can be matched later in the string with the

>>> re.split('\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split('\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
4 special sequence, described below. To match the literals
>>> re.split('\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split('\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
3 or
>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
42, use
>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
70 or
>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
71, or enclose them inside a character class:
>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
72.

>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
73

This is an extension notation (a

>>> re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',
...        r'static PyObject*\npy_\1(void)\n{',
...        'def myfunc():')
'static PyObject*\npy_myfunc(void)\n{'
0 following a
>>> re.split('\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split('\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
3 is not meaningful otherwise). The first character after the
>>> re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',
...        r'static PyObject*\npy_\1(void)\n{',
...        'def myfunc():')
'static PyObject*\npy_myfunc(void)\n{'
0 determines what the meaning and further syntax of the construct is. Extensions usually do not create a new group;
>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
77 is the only exception to this rule. Following are the currently supported extensions.

>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
78

(One or more letters from the set

>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
79,
>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
80,
>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
26,
>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
82,
>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
83,
>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
84.) The group matches the empty string; the letters set the corresponding flags: (ignore case), (locale dependent), (multi-line), (dot matches all), (Unicode dependent), and (verbose), for the entire regular expression. (The flags are described in .) This is useful if you wish to include the flags as part of the regular expression, instead of passing a flag argument to the function.

Note that the

>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
92 flag changes how the expression is parsed. It should be used first in the expression string, or after one or more whitespace characters. If there are non-whitespace characters before the flag, the results are undefined.

>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
93

A non-capturing version of regular parentheses. Matches whatever regular expression is inside the parentheses, but the substring matched by the group cannot be retrieved after performing a match or referenced later in the pattern.

>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
77

Similar to regular parentheses, but the substring matched by the group is accessible via the symbolic group name name. Group names must be valid Python identifiers, and each group name must be defined only once within a regular expression. A symbolic group is also a numbered group, just as if the group were not named.

Named groups can be referenced in three contexts. If the pattern is

>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
95 (i.e. matching a string quoted with either single or double quotes):

Context of reference to group “quote”

Ways to reference it

in the same pattern itself

  • >>> m = re.search('(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    96 (as shown)

  • >>> m = re.search('(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    97

when processing match object

>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
98

  • >>> m = re.search('(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    99

  • \a      \b      \f      \n
    \r      \t      \v      \x
    \\
    
    00 (etc.)

in a string passed to the

\a      \b      \f      \n
\r      \t      \v      \x
\\
01 argument of
\a      \b      \f      \n
\r      \t      \v      \x
\\
02

  • \a      \b      \f      \n
    \r      \t      \v      \x
    \\
    
    03

  • \a      \b      \f      \n
    \r      \t      \v      \x
    \\
    
    04

  • >>> m = re.search('(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    97

\a      \b      \f      \n
\r      \t      \v      \x
\\
06

A backreference to a named group; it matches whatever text was matched by the earlier group named name.

\a      \b      \f      \n
\r      \t      \v      \x
\\
07

A comment; the contents of the parentheses are simply ignored.

\a      \b      \f      \n
\r      \t      \v      \x
\\
08

Matches if

\a      \b      \f      \n
\r      \t      \v      \x
\\
09 matches next, but doesn’t consume any of the string. This is called a lookahead assertion. For example,
\a      \b      \f      \n
\r      \t      \v      \x
\\
10 will match
\a      \b      \f      \n
\r      \t      \v      \x
\\
11 only if it’s followed by
\a      \b      \f      \n
\r      \t      \v      \x
\\
12.

\a      \b      \f      \n
\r      \t      \v      \x
\\
13

Matches if

\a      \b      \f      \n
\r      \t      \v      \x
\\
09 doesn’t match next. This is a negative lookahead assertion. For example,
\a      \b      \f      \n
\r      \t      \v      \x
\\
15 will match
\a      \b      \f      \n
\r      \t      \v      \x
\\
11 only if it’s not followed by
\a      \b      \f      \n
\r      \t      \v      \x
\\
12.

\a      \b      \f      \n
\r      \t      \v      \x
\\
18

Matches if the current position in the string is preceded by a match for

\a      \b      \f      \n
\r      \t      \v      \x
\\
09 that ends at the current position. This is called a positive lookbehind assertion.
\a      \b      \f      \n
\r      \t      \v      \x
\\
20 will find a match in
\a      \b      \f      \n
\r      \t      \v      \x
\\
21, since the lookbehind will back up 3 characters and check if the contained pattern matches. The contained pattern must only match strings of some fixed length, meaning that
\a      \b      \f      \n
\r      \t      \v      \x
\\
22 or
\a      \b      \f      \n
\r      \t      \v      \x
\\
23 are allowed, but
\a      \b      \f      \n
\r      \t      \v      \x
\\
24 and
\a      \b      \f      \n
\r      \t      \v      \x
\\
25 are not. Group references are not supported even if they match strings of some fixed length. Note that patterns which start with positive lookbehind assertions will not match at the beginning of the string being searched; you will most likely want to use the function rather than the function:

>>> import re
>>> m = re.search('(?<=abc)def', 'abcdef')
>>> m.group(0)
'def'

This example looks for a word following a hyphen:

>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'

\a      \b      \f      \n
\r      \t      \v      \x
\\
28

Matches if the current position in the string is not preceded by a match for

\a      \b      \f      \n
\r      \t      \v      \x
\\
09. This is called a negative lookbehind assertion. Similar to positive lookbehind assertions, the contained pattern must only match strings of some fixed length and shouldn’t contain group references. Patterns which start with negative lookbehind assertions may match at the beginning of the string being searched.

\a      \b      \f      \n
\r      \t      \v      \x
\\
30

Will try to match with

\a      \b      \f      \n
\r      \t      \v      \x
\\
31 if the group with given id or name exists, and with
\a      \b      \f      \n
\r      \t      \v      \x
\\
32 if it doesn’t.
\a      \b      \f      \n
\r      \t      \v      \x
\\
32 is optional and can be omitted. For example,
\a      \b      \f      \n
\r      \t      \v      \x
\\
34 is a poor email matching pattern, which will match with
\a      \b      \f      \n
\r      \t      \v      \x
\\
35 as well as
\a      \b      \f      \n
\r      \t      \v      \x
\\
36, but not with
\a      \b      \f      \n
\r      \t      \v      \x
\\
37.

New in version 2.4.

The special sequences consist of

result = re.match(pattern, string)
4 and a character from the list below. If the ordinary character is not on the list, then the resulting RE will match the second character. For example,
\a      \b      \f      \n
\r      \t      \v      \x
\\
39 matches the character
>>> re.split('(\W+)', '...words, words...')
['', '...', 'words', ', ', 'words', '...', '']
7.

>>> re.split('\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split('\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
4

Matches the contents of the group of the same number. Groups are numbered starting from 1. For example,

\a      \b      \f      \n
\r      \t      \v      \x
\\
42 matches
\a      \b      \f      \n
\r      \t      \v      \x
\\
43 or
\a      \b      \f      \n
\r      \t      \v      \x
\\
44, but not
\a      \b      \f      \n
\r      \t      \v      \x
\\
45 (note the space after the group). This special sequence can only be used to match one of the first 99 groups. If the first digit of number is 0, or number is 3 octal digits long, it will not be interpreted as a group match, but as the character with octal value number. Inside the
\a      \b      \f      \n
\r      \t      \v      \x
\\
46 and
>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
53 of a character class, all numeric escapes are treated as characters.

\a      \b      \f      \n
\r      \t      \v      \x
\\
48

Matches only at the start of the string.

\a      \b      \f      \n
\r      \t      \v      \x
\\
49

Matches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of alphanumeric or underscore characters, so the end of a word is indicated by whitespace or a non-alphanumeric, non-underscore character. Note that formally,

\a      \b      \f      \n
\r      \t      \v      \x
\\
49 is defined as the boundary between a
>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
43 and a
\a      \b      \f      \n
\r      \t      \v      \x
\\
52 character (or vice versa), or between
>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
43 and the beginning/end of the string, so the precise set of characters deemed to be alphanumeric depends on the values of the
>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
46 and
>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
45 flags. For example,
\a      \b      \f      \n
\r      \t      \v      \x
\\
56 matches
\a      \b      \f      \n
\r      \t      \v      \x
\\
57,
\a      \b      \f      \n
\r      \t      \v      \x
\\
58,
\a      \b      \f      \n
\r      \t      \v      \x
\\
59,
\a      \b      \f      \n
\r      \t      \v      \x
\\
60 but not
\a      \b      \f      \n
\r      \t      \v      \x
\\
61 or
\a      \b      \f      \n
\r      \t      \v      \x
\\
62. Inside a character range,
\a      \b      \f      \n
\r      \t      \v      \x
\\
49 represents the backspace character, for compatibility with Python’s string literals.

\a      \b      \f      \n
\r      \t      \v      \x
\\
64

Matches the empty string, but only when it is not at the beginning or end of a word. This means that

\a      \b      \f      \n
\r      \t      \v      \x
\\
65 matches
\a      \b      \f      \n
\r      \t      \v      \x
\\
66,
\a      \b      \f      \n
\r      \t      \v      \x
\\
67,
\a      \b      \f      \n
\r      \t      \v      \x
\\
68, but not
\a      \b      \f      \n
\r      \t      \v      \x
\\
69,
\a      \b      \f      \n
\r      \t      \v      \x
\\
70, or
\a      \b      \f      \n
\r      \t      \v      \x
\\
71.
\a      \b      \f      \n
\r      \t      \v      \x
\\
64 is just the opposite of
\a      \b      \f      \n
\r      \t      \v      \x
\\
49, so is also subject to the settings of
>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
45 and
>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
46.

\a      \b      \f      \n
\r      \t      \v      \x
\\
76

When the flag is not specified, matches any decimal digit; this is equivalent to the set

\a      \b      \f      \n
\r      \t      \v      \x
\\
78. With , it will match whatever is classified as a decimal digit in the Unicode character properties database.

\a      \b      \f      \n
\r      \t      \v      \x
\\
80

When the flag is not specified, matches any non-digit character; this is equivalent to the set

\a      \b      \f      \n
\r      \t      \v      \x
\\
82. With , it will match anything other than character marked as digits in the Unicode character properties database.

\a      \b      \f      \n
\r      \t      \v      \x
\\
84

When the flag is not specified, it matches any whitespace character, this is equivalent to the set

\a      \b      \f      \n
\r      \t      \v      \x
\\
86. The flag has no extra effect on matching of the space. If is set, this will match the characters
\a      \b      \f      \n
\r      \t      \v      \x
\\
86 plus whatever is classified as space in the Unicode character properties database.

>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
44

When the flag is not specified, matches any non-whitespace character; this is equivalent to the set

\a      \b      \f      \n
\r      \t      \v      \x
\\
92 The flag has no extra effect on non-whitespace match. If is set, then any character not marked as space in the Unicode character properties database is matched.

>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
43

When the and flags are not specified, matches any alphanumeric character and the underscore; this is equivalent to the set

\a      \b      \f      \n
\r      \t      \v      \x
\\
98. With , it will match the set
prog = re.compile(pattern)
result = prog.match(string)
00 plus whatever characters are defined as alphanumeric for the current locale. If is set, this will match the characters
prog = re.compile(pattern)
result = prog.match(string)
00 plus whatever is classified as alphanumeric in the Unicode character properties database.

\a      \b      \f      \n
\r      \t      \v      \x
\\
52

When the and flags are not specified, matches any non-alphanumeric character; this is equivalent to the set

prog = re.compile(pattern)
result = prog.match(string)
06. With , it will match any character not in the set
prog = re.compile(pattern)
result = prog.match(string)
00, and not defined as alphanumeric for the current locale. If is set, this will match anything other than
prog = re.compile(pattern)
result = prog.match(string)
00 plus characters classified as not alphanumeric in the Unicode character properties database.

prog = re.compile(pattern)
result = prog.match(string)
11

Matches only at the end of the string.

If both and flags are included for a particular sequence, then flag takes effect first followed by the .

Most of the standard escapes supported by Python string literals are also accepted by the regular expression parser:

\a      \b      \f      \n
\r      \t      \v      \x
\\

(Note that

\a      \b      \f      \n
\r      \t      \v      \x
\\
49 is used to represent word boundaries, and means “backspace” only inside character classes.)

Octal escapes are included in a limited form: If the first digit is a 0, or if there are three octal digits, it is considered an octal escape. Otherwise, it is a group reference. As for string literals, octal escapes are always at most three digits in length.

See also

Mastering Regular Expressions

Book on regular expressions by Jeffrey Friedl, published by O’Reilly. The second edition of the book no longer covers Python at all, but the first edition covered writing good regular expression patterns in great detail.

7.2.2. Module Contents

The module defines several functions, constants, and an exception. Some of the functions are simplified versions of the full featured methods for compiled regular expressions. Most non-trivial applications always use the compiled form.

prog = re.compile(pattern)
result = prog.match(string)
17
prog = re.compile(pattern)
result = prog.match(string)
18(pattern, flags=0)

Compile a regular expression pattern into a regular expression object, which can be used for matching using its and methods, described below.

The expression’s behaviour can be modified by specifying a flags value. Values can be any of the following variables, combined using bitwise OR (the

prog = re.compile(pattern)
result = prog.match(string)
21 operator).

The sequence

prog = re.compile(pattern)
result = prog.match(string)

is equivalent to

result = re.match(pattern, string)

but using and saving the resulting regular expression object for reuse is more efficient when the expression will be used several times in a single program.

Note

The compiled versions of the most recent patterns passed to , or are cached, so programs that use only a few regular expressions at a time needn’t worry about compiling regular expressions.

prog = re.compile(pattern)
result = prog.match(string)
17
prog = re.compile(pattern)
result = prog.match(string)
27

Display debug information about compiled expression.

prog = re.compile(pattern)
result = prog.match(string)
17
prog = re.compile(pattern)
result = prog.match(string)
29
prog = re.compile(pattern)
result = prog.match(string)
17
prog = re.compile(pattern)
result = prog.match(string)
31

Perform case-insensitive matching; expressions like

prog = re.compile(pattern)
result = prog.match(string)
32 will match lowercase letters, too. This is not affected by the current locale. To get this effect on non-ASCII Unicode characters such as
prog = re.compile(pattern)
result = prog.match(string)
33 and
prog = re.compile(pattern)
result = prog.match(string)
34, add the flag.

prog = re.compile(pattern)
result = prog.match(string)
17
prog = re.compile(pattern)
result = prog.match(string)
37
prog = re.compile(pattern)
result = prog.match(string)
17
prog = re.compile(pattern)
result = prog.match(string)
39

Make

>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
43,
\a      \b      \f      \n
\r      \t      \v      \x
\\
52,
\a      \b      \f      \n
\r      \t      \v      \x
\\
49,
\a      \b      \f      \n
\r      \t      \v      \x
\\
64,
\a      \b      \f      \n
\r      \t      \v      \x
\\
84 and
>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
44 dependent on the current locale.

prog = re.compile(pattern)
result = prog.match(string)
17
prog = re.compile(pattern)
result = prog.match(string)
47
prog = re.compile(pattern)
result = prog.match(string)
17
prog = re.compile(pattern)
result = prog.match(string)
49

When specified, the pattern character

>>> re.split('(\W+)', '...words, words...')
['', '...', 'words', ', ', 'words', '...', '']
5 matches at the beginning of the string and at the beginning of each line (immediately following each newline); and the pattern character
>>> re.split('(\W+)', '...words, words...')
['', '...', 'words', ', ', 'words', '...', '']
7 matches at the end of the string and at the end of each line (immediately preceding each newline). By default,
>>> re.split('(\W+)', '...words, words...')
['', '...', 'words', ', ', 'words', '...', '']
5 matches only at the beginning of the string, and
>>> re.split('(\W+)', '...words, words...')
['', '...', 'words', ', ', 'words', '...', '']
7 only at the end of the string and immediately before the newline (if any) at the end of the string.

prog = re.compile(pattern)
result = prog.match(string)
17
prog = re.compile(pattern)
result = prog.match(string)
55
prog = re.compile(pattern)
result = prog.match(string)
17
prog = re.compile(pattern)
result = prog.match(string)
57

Make the

>>> re.split('(\W+)', '...words, words...')
['', '...', 'words', ', ', 'words', '...', '']
3 special character match any character at all, including a newline; without this flag,
>>> re.split('(\W+)', '...words, words...')
['', '...', 'words', ', ', 'words', '...', '']
3 will match anything except a newline.

prog = re.compile(pattern)
result = prog.match(string)
17
prog = re.compile(pattern)
result = prog.match(string)
61
prog = re.compile(pattern)
result = prog.match(string)
17
prog = re.compile(pattern)
result = prog.match(string)
63

Make the

>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
43,
\a      \b      \f      \n
\r      \t      \v      \x
\\
52,
\a      \b      \f      \n
\r      \t      \v      \x
\\
49,
\a      \b      \f      \n
\r      \t      \v      \x
\\
64,
\a      \b      \f      \n
\r      \t      \v      \x
\\
76,
\a      \b      \f      \n
\r      \t      \v      \x
\\
80,
\a      \b      \f      \n
\r      \t      \v      \x
\\
84 and
>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
44 sequences dependent on the Unicode character properties database. Also enables non-ASCII matching for .

New in version 2.0.

prog = re.compile(pattern)
result = prog.match(string)
17
prog = re.compile(pattern)
result = prog.match(string)
74
prog = re.compile(pattern)
result = prog.match(string)
17
prog = re.compile(pattern)
result = prog.match(string)
76

This flag allows you to write regular expressions that look nicer and are more readable by allowing you to visually separate logical sections of the pattern and add comments. Whitespace within the pattern is ignored, except when in a character class, or when preceded by an unescaped backslash, or within tokens like

>>> re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',
...        r'static PyObject*\npy_\1(void)\n{',
...        'def myfunc():')
'static PyObject*\npy_myfunc(void)\n{'
2,
prog = re.compile(pattern)
result = prog.match(string)
78 or
prog = re.compile(pattern)
result = prog.match(string)
79. When a line contains a
prog = re.compile(pattern)
result = prog.match(string)
80 that is not in a character class and is not preceded by an unescaped backslash, all characters from the leftmost such
prog = re.compile(pattern)
result = prog.match(string)
80 through the end of the line are ignored.

This means that the two following regular expression objects that match a decimal number are functionally equal:

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")

prog = re.compile(pattern)
result = prog.match(string)
17
prog = re.compile(pattern)
result = prog.match(string)
83(pattern, string, flags=0)

Scan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding instance. Return

prog = re.compile(pattern)
result = prog.match(string)
85 if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.

prog = re.compile(pattern)
result = prog.match(string)
17
prog = re.compile(pattern)
result = prog.match(string)
87(pattern, string, flags=0)

If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding instance. Return

prog = re.compile(pattern)
result = prog.match(string)
85 if the string does not match the pattern; note that this is different from a zero-length match.

Note that even in mode, will only match at the beginning of the string and not at the beginning of each line.

If you want to locate a match anywhere in string, use instead (see also ).

prog = re.compile(pattern)
result = prog.match(string)
17
prog = re.compile(pattern)
result = prog.match(string)
94(pattern, string, maxsplit=0, flags=0)

Split string by the occurrences of pattern. If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list. If maxsplit is nonzero, at most maxsplit splits occur, and the remainder of the string is returned as the final element of the list. (Incompatibility note: in the original Python 1.5 release, maxsplit was ignored. This has been fixed in later releases.)

>>> re.split('\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split('\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']

If there are capturing groups in the separator and it matches at the start of the string, the result will start with an empty string. The same holds for the end of the string:

>>> re.split('(\W+)', '...words, words...')
['', '...', 'words', ', ', 'words', '...', '']

That way, separator components are always found at the same relative indices within the result list (e.g., if there’s one capturing group in the separator, the 0th, the 2nd and so forth).

Note that split will never split a string on an empty pattern match. For example:

>>> re.split('x*', 'foo')
['foo']
>>> re.split("(?m)^$", "foo\n\nbar\n")
['foo\n\nbar\n']

Changed in version 2.7: Added the optional flags argument.

prog = re.compile(pattern)
result = prog.match(string)
17
prog = re.compile(pattern)
result = prog.match(string)
96(pattern, string, flags=0)

Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result.

Note

Due to the limitation of the current implementation the character following an empty match is not included in a next match, so

prog = re.compile(pattern)
result = prog.match(string)
97 returns
prog = re.compile(pattern)
result = prog.match(string)
98 (note missed “t”). This is changed in Python 3.7.

New in version 1.5.2.

Changed in version 2.4: Added the optional flags argument.

prog = re.compile(pattern)
result = prog.match(string)
17
result = re.match(pattern, string)
00(pattern, string, flags=0)

Return an yielding instances over all non-overlapping matches for the RE pattern in string. The string is scanned left-to-right, and matches are returned in the order found. Empty matches are included in the result. See also the note about .

New in version 2.2.

Changed in version 2.4: Added the optional flags argument.

prog = re.compile(pattern)
result = prog.match(string)
17
result = re.match(pattern, string)
04(pattern, repl, string, count=0, flags=0)

Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isn’t found, string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed. That is,

result = re.match(pattern, string)
05 is converted to a single newline character,
result = re.match(pattern, string)
06 is converted to a carriage return, and so forth. Unknown escapes such as
result = re.match(pattern, string)
07 are left alone. Backreferences, such as
result = re.match(pattern, string)
08, are replaced with the substring matched by group 6 in the pattern. For example:

>>> re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',
...        r'static PyObject*\npy_\1(void)\n{',
...        'def myfunc():')
'static PyObject*\npy_myfunc(void)\n{'

If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string. For example:

>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
0

The pattern may be a string or an RE object.

The optional argument count is the maximum number of pattern occurrences to be replaced; count must be a non-negative integer. If omitted or zero, all occurrences will be replaced. Empty matches for the pattern are replaced only when not adjacent to a previous match, so

result = re.match(pattern, string)
09 returns
result = re.match(pattern, string)
10.

In string-type repl arguments, in addition to the character escapes and backreferences described above,

result = re.match(pattern, string)
11 will use the substring matched by the group named
result = re.match(pattern, string)
12, as defined by the
>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
77 syntax.
result = re.match(pattern, string)
14 uses the corresponding group number;
result = re.match(pattern, string)
15 is therefore equivalent to
result = re.match(pattern, string)
16, but isn’t ambiguous in a replacement such as
result = re.match(pattern, string)
17.
result = re.match(pattern, string)
18 would be interpreted as a reference to group 20, not a reference to group 2 followed by the literal character
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
7. The backreference
result = re.match(pattern, string)
20 substitutes in the entire substring matched by the RE.

Changed in version 2.7: Added the optional flags argument.

prog = re.compile(pattern)
result = prog.match(string)
17
result = re.match(pattern, string)
22(pattern, repl, string, count=0, flags=0)

Perform the same operation as , but return a tuple

result = re.match(pattern, string)
24.

Changed in version 2.7: Added the optional flags argument.

prog = re.compile(pattern)
result = prog.match(string)
17
result = re.match(pattern, string)
26(pattern)

Escape all the characters in pattern except ASCII letters and numbers. This is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it. For example:

>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
1

prog = re.compile(pattern)
result = prog.match(string)
17
result = re.match(pattern, string)
28()

Clear the regular expression cache.

exception
prog = re.compile(pattern)
result = prog.match(string)
17
result = re.match(pattern, string)
30

Exception raised when a string passed to one of the functions here is not a valid regular expression (for example, it might contain unmatched parentheses) or when some other error occurs during compilation or matching. It is never an error if a string contains no match for a pattern.

7.2.3. Regular Expression Objects

class
prog = re.compile(pattern)
result = prog.match(string)
17
result = re.match(pattern, string)
32

The class supports the following methods and attributes:

prog = re.compile(pattern)
result = prog.match(string)
83(string[, pos[, endpos]])

Scan through string looking for a location where this regular expression produces a match, and return a corresponding instance. Return

prog = re.compile(pattern)
result = prog.match(string)
85 if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.

The optional second parameter pos gives an index in the string where the search is to start; it defaults to

result = re.match(pattern, string)
37. This is not completely equivalent to slicing the string; the
>>> re.split('(\W+)', '...words, words...')
['', '...', 'words', ', ', 'words', '...', '']
5 pattern character matches at the real beginning of the string and at positions just after a newline, but not necessarily at the index where the search is to start.

The optional parameter endpos limits how far the string will be searched; it will be as if the string is endpos characters long, so only the characters from pos to

result = re.match(pattern, string)
39 will be searched for a match. If endpos is less than pos, no match will be found, otherwise, if rx is a compiled regular expression object,
result = re.match(pattern, string)
40 is equivalent to
result = re.match(pattern, string)
41.

>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
2

prog = re.compile(pattern)
result = prog.match(string)
87(string[, pos[, endpos]])

If zero or more characters at the beginning of string match this regular expression, return a corresponding instance. Return

prog = re.compile(pattern)
result = prog.match(string)
85 if the string does not match the pattern; note that this is different from a zero-length match.

The optional pos and endpos parameters have the same meaning as for the method.

>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
3

If you want to locate a match anywhere in string, use instead (see also ).

prog = re.compile(pattern)
result = prog.match(string)
94(string, maxsplit=0)

Identical to the function, using the compiled pattern.

prog = re.compile(pattern)
result = prog.match(string)
96(string[, pos[, endpos]])

Similar to the function, using the compiled pattern, but also accepts optional pos and endpos parameters that limit the search region like for .

result = re.match(pattern, string)
00(string[, pos[, endpos]])

Similar to the function, using the compiled pattern, but also accepts optional pos and endpos parameters that limit the search region like for .

result = re.match(pattern, string)
04(repl, string, count=0)

Identical to the function, using the compiled pattern.

result = re.match(pattern, string)
22(repl, string, count=0)

Identical to the function, using the compiled pattern.

result = re.match(pattern, string)
59

The regex matching flags. This is a combination of the flags given to and any

>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
73 inline flags in the pattern.

result = re.match(pattern, string)
62

The number of capturing groups in the pattern.

result = re.match(pattern, string)
63

A dictionary mapping any symbolic group names defined by

result = re.match(pattern, string)
64 to group numbers. The dictionary is empty if no symbolic groups were used in the pattern.

result = re.match(pattern, string)
65

The pattern string from which the RE object was compiled.

7.2.4. Match Objects

class
prog = re.compile(pattern)
result = prog.match(string)
17
result = re.match(pattern, string)
67

Match objects always have a boolean value of

result = re.match(pattern, string)
68. Since
\a      \b      \f      \n
\r      \t      \v      \x
\\
27 and
\a      \b      \f      \n
\r      \t      \v      \x
\\
26 return
prog = re.compile(pattern)
result = prog.match(string)
85 when there is no match, you can test whether there was a match with a simple
result = re.match(pattern, string)
72 statement:

>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
4

Match objects support the following methods and attributes:

result = re.match(pattern, string)
73(template)

Return the string obtained by doing backslash substitution on the template string template, as done by the method. Escapes such as

result = re.match(pattern, string)
05 are converted to the appropriate characters, and numeric backreferences (
>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
97,
result = re.match(pattern, string)
16) and named backreferences (
\a      \b      \f      \n
\r      \t      \v      \x
\\
04,
result = re.match(pattern, string)
11) are replaced by the contents of the corresponding group.

result = re.match(pattern, string)
80([group1, ...])

Returns one or more subgroups of the match. If there is a single argument, the result is a single string; if there are multiple arguments, the result is a tuple with one item per argument. Without arguments, group1 defaults to zero (the whole match is returned). If a groupN argument is zero, the corresponding return value is the entire matching string; if it is in the inclusive range [1..99], it is the string matching the corresponding parenthesized group. If a group number is negative or larger than the number of groups defined in the pattern, an exception is raised. If a group is contained in a part of the pattern that did not match, the corresponding result is

prog = re.compile(pattern)
result = prog.match(string)
85. If a group is contained in a part of the pattern that matched multiple times, the last match is returned.

>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
5

If the regular expression uses the

>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
77 syntax, the groupN arguments may also be strings identifying groups by their group name. If a string argument is not used as a group name in the pattern, an exception is raised.

A moderately complicated example:

>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
6

Named groups can also be referred to by their index:

>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
7

If a group matches multiple times, only the last match is accessible:

>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
8

result = re.match(pattern, string)
62([default])

Return a tuple containing all the subgroups of the match, from 1 up to however many groups are in the pattern. The default argument is used for groups that did not participate in the match; it defaults to

prog = re.compile(pattern)
result = prog.match(string)
85. (Incompatibility note: in the original Python 1.5 release, if the tuple was one element long, a string would be returned instead. In later versions (from 1.5.1 on), a singleton tuple is returned in such cases.)

For example:

>>> m = re.search('(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
9

If we make the decimal place and everything after it optional, not all groups might participate in the match. These groups will default to

prog = re.compile(pattern)
result = prog.match(string)
85 unless the default argument is given:

\a      \b      \f      \n
\r      \t      \v      \x
\\
0

result = re.match(pattern, string)
88([default])

Return a dictionary containing all the named subgroups of the match, keyed by the subgroup name. The default argument is used for groups that did not participate in the match; it defaults to

prog = re.compile(pattern)
result = prog.match(string)
85. For example:

\a      \b      \f      \n
\r      \t      \v      \x
\\
1

result = re.match(pattern, string)
90([group])
result = re.match(pattern, string)
91([group])

Return the indices of the start and end of the substring matched by group; group defaults to zero (meaning the whole matched substring). Return

result = re.match(pattern, string)
92 if group exists but did not contribute to the match. For a match object m, and a group g that did contribute to the match, the substring matched by group g (equivalent to
result = re.match(pattern, string)
93) is

\a      \b      \f      \n
\r      \t      \v      \x
\\
2

Note that

result = re.match(pattern, string)
94 will equal
result = re.match(pattern, string)
95 if group matched a null string. For example, after
result = re.match(pattern, string)
96,
result = re.match(pattern, string)
97 is 1,
result = re.match(pattern, string)
98 is 2,
result = re.match(pattern, string)
99 and
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
00 are both 2, and
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
01 raises an exception.

An example that will remove remove_this from email addresses:

\a      \b      \f      \n
\r      \t      \v      \x
\\
3

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
03([group])

For m, return the 2-tuple

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
05. Note that if group did not contribute to the match, this is
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
06. group defaults to zero, the entire match.

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
07

The value of pos which was passed to the or method of the . This is the index into the string at which the RE engine started looking for a match.

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
11

The value of endpos which was passed to the or method of the . This is the index into the string beyond which the RE engine will not go.

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
15

The integer index of the last matched capturing group, or

prog = re.compile(pattern)
result = prog.match(string)
85 if no group was matched at all. For example, the expressions
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
17,
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
18, and
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
19 will have
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
20 if applied to the string
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
21, while the expression
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
22 will have
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
23, if applied to the same string.

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
24

The name of the last matched capturing group, or

prog = re.compile(pattern)
result = prog.match(string)
85 if the group didn’t have a name, or if no group was matched at all.

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
26

The regular expression object whose or method produced this instance.

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
30

The string passed to or .

7.2.5. Examples

7.2.5.1. Checking For a Pair

In this example, we’ll use the following helper function to display match objects a little more gracefully:

\a      \b      \f      \n
\r      \t      \v      \x
\\
4

Suppose you are writing a poker program where a player’s hand is represented as a 5-character string with each character representing a card, “a” for ace, “k” for king, “q” for queen, “j” for jack, “t” for 10, and “2” through “9” representing the card with that value.

To see if a given string is a valid hand, one could do the following:

\a      \b      \f      \n
\r      \t      \v      \x
\\
5

That last hand,

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
33, contained a pair, or two of the same valued cards. To match this with a regular expression, one could use backreferences as such:

\a      \b      \f      \n
\r      \t      \v      \x
\\
6

To find out what card the pair consists of, one could use the method of in the following manner:

\a      \b      \f      \n
\r      \t      \v      \x
\\
7

7.2.5.2. Simulating scanf()

Python does not currently have an equivalent to

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
36. Regular expressions are generally more powerful, though also more verbose, than
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
36 format strings. The table below offers some more-or-less equivalent mappings between
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
36 format tokens and regular expressions.

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
36 Token

Regular Expression

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
40

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
41

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
42

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
43

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
44

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
45

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
46,
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
47,
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
48,
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
49

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
50

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
51

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
52

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
53

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
54

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
55

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
56

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
57

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
58

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
59,
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
60

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
61

To extract the filename and numbers from a string like

\a      \b      \f      \n
\r      \t      \v      \x
\\
8

you would use a

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
36 format like

\a      \b      \f      \n
\r      \t      \v      \x
\\
9

The equivalent regular expression would be

prog = re.compile(pattern)
result = prog.match(string)
0

7.2.5.3. search() vs. match()

Python offers two different primitive operations based on regular expressions: checks for a match only at the beginning of the string, while checks for a match anywhere in the string (this is what Perl does by default).

For example:

prog = re.compile(pattern)
result = prog.match(string)
1

Regular expressions beginning with

>>> re.split('(\W+)', '...words, words...')
['', '...', 'words', ', ', 'words', '...', '']
5 can be used with to restrict the match at the beginning of the string:

prog = re.compile(pattern)
result = prog.match(string)
2

Note however that in mode only matches at the beginning of the string, whereas using with a regular expression beginning with

>>> re.split('(\W+)', '...words, words...')
['', '...', 'words', ', ', 'words', '...', '']
5 will match at the beginning of each line.

prog = re.compile(pattern)
result = prog.match(string)
3

7.2.5.4. Making a Phonebook

splits a string into a list delimited by the passed pattern. The method is invaluable for converting textual data into data structures that can be easily read and modified by Python as demonstrated in the following example that creates a phonebook.

First, here is the input. Normally it may come from a file, here we are using triple-quoted string syntax:

prog = re.compile(pattern)
result = prog.match(string)
4

The entries are separated by one or more newlines. Now we convert the string into a list with each nonempty line having its own entry:

prog = re.compile(pattern)
result = prog.match(string)
5

Finally, split each entry into a list with first name, last name, telephone number, and address. We use the

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
72 parameter of because the address has spaces, our splitting pattern, in it:

prog = re.compile(pattern)
result = prog.match(string)
6

The

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
74 pattern matches the colon after the last name, so that it does not occur in the result list. With a
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
72 of
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
76, we could separate the house number from the street name:

prog = re.compile(pattern)
result = prog.match(string)
7

7.2.5.5. Text Munging

replaces every occurrence of a pattern with a string or the result of a function. This example demonstrates using with a function to “munge” text, or randomize the order of all the characters in each word of a sentence except for the first and last characters:

prog = re.compile(pattern)
result = prog.match(string)
8

7.2.5.6. Finding all Adverbs

matches all occurrences of a pattern, not just the first one as does. For example, if a writer wanted to find all of the adverbs in some text, they might use in the following manner:

prog = re.compile(pattern)
result = prog.match(string)
9

7.2.5.7. Finding all Adverbs and their Positions

If one wants more information about all matches of a pattern than the matched text, is useful as it provides instances of instead of strings. Continuing with the previous example, if a writer wanted to find all of the adverbs and their positions in some text, they would use in the following manner:

result = re.match(pattern, string)
0

7.2.5.8. Raw String Notation

Raw string notation (

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
85) keeps regular expressions sane. Without it, every backslash (
result = re.match(pattern, string)
4) in a regular expression would have to be prefixed with another one to escape it. For example, the two following lines of code are functionally identical:

result = re.match(pattern, string)
1

When one wants to match a literal backslash, it must be escaped in the regular expression. With raw string notation, this means

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
87. Without raw string notation, one must use
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
88, making the following lines of code functionally identical: