Hướng dẫn dùng re escape python

Both patterns and strings to be searched can be Unicode strings (

prog = re.compile(pattern)
result = prog.match(string)
2) as well as 8-bit strings (
prog = re.compile(pattern)
result = prog.match(string)
3). However, Unicode strings and 8-bit strings cannot be mixed: that is, you cannot match a Unicode string with a byte pattern or vice-versa; similarly, when asking for a substitution, the replacement string must be of the same type as both the pattern and the search string.

Regular expressions use the backslash character (

prog = re.compile(pattern)
result = prog.match(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
prog = re.compile(pattern)
result = prog.match(string)
5 as the pattern string, because the regular expression must be
prog = re.compile(pattern)
result = prog.match(string)
6, and each backslash must be expressed as
prog = re.compile(pattern)
result = prog.match(string)
6 inside a regular Python string literal. Also, please note that any invalid escape sequences in Python’s usage of the backslash in string literals now generate a
prog = re.compile(pattern)
result = prog.match(string)
8 and in the future this will become a
prog = re.compile(pattern)
result = prog.match(string)
9. This behaviour will happen even if it is a valid escape sequence for a regular expression.

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)
0. So
result = re.match(pattern, string)
1 is a two-character string containing
prog = re.compile(pattern)
result = prog.match(string)
4 and
result = re.match(pattern, string)
3, while
result = re.match(pattern, string)
4 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 on compiled regular expressions. 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

prog = re.compile(pattern)
result = prog.match(string)
1 module, but offers additional functionality and a more thorough Unicode support.

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 [Frie09], 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 Expression HOWTO.

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

result = re.match(pattern, string)
6,
result = re.match(pattern, string)
7, or
result = re.match(pattern, string)
8, are the simplest regular expressions; they simply match themselves. You can concatenate ordinary characters, so
result = re.match(pattern, string)
9 matches the string
>>> re.split(r'\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split(r'(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split(r'\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
0. (In the rest of this section, we’ll write RE’s in
>>> re.split(r'\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split(r'(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split(r'\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
1, usually without quotes, and strings to be matched
>>> re.split(r'\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split(r'(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split(r'\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
2.)

Some characters, like

>>> re.split(r'\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split(r'(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split(r'\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
3 or
>>> re.split(r'\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split(r'(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split(r'\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
4, are special. Special characters either stand for classes of ordinary characters, or affect how the regular expressions around them are interpreted.

Repetition operators or quantifiers (

>>> re.split(r'\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split(r'(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split(r'\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
5,
>>> re.split(r'\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split(r'(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split(r'\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
6,
>>> re.split(r'\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split(r'(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split(r'\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
7,
>>> re.split(r'\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split(r'(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split(r'\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
8, etc) cannot be directly nested. This avoids ambiguity with the non-greedy modifier suffix
>>> re.split(r'\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split(r'(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split(r'\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
7, 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(r'(\W+)', '...words, words...')
['', '...', 'words', ', ', 'words', '...', '']
0 matches any multiple of six
result = re.match(pattern, string)
7 characters.

The special characters are:

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

(Dot.) In the default mode, this matches any character except a newline. If the

>>> re.split(r'(\W+)', '...words, words...')
['', '...', 'words', ', ', 'words', '...', '']
3 flag has been specified, this matches any character including a newline.

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

(Caret.) Matches the start of the string, and in

>>> re.split(r'(\W+)', '...words, words...')
['', '...', 'words', ', ', 'words', '...', '']
5 mode also matches immediately after each newline.

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

Matches the end of the string or just before the newline at the end of the string, and in

>>> re.split(r'(\W+)', '...words, words...')
['', '...', 'words', ', ', 'words', '...', '']
5 mode also matches before a newline.
>>> re.split(r'(\W+)', '...words, words...')
['', '...', 'words', ', ', 'words', '...', '']
8 matches both ‘foo’ and ‘foobar’, while the regular expression
>>> re.split(r'(\W+)', '...words, words...')
['', '...', 'words', ', ', 'words', '...', '']
9 matches only ‘foo’. More interestingly, searching for
>>> re.split(r'\b', 'Words, words, words.')
['', 'Words', ', ', 'words', ', ', 'words', '.']
>>> re.split(r'\W*', '...words...')
['', '', 'w', 'o', 'r', 'd', 's', '', '']
>>> re.split(r'(\W*)', '...words...')
['', '...', '', '', 'w', '', 'o', '', 'r', '', 'd', '', 's', '...', '', '', '']
0 in
>>> re.split(r'\b', 'Words, words, words.')
['', 'Words', ', ', 'words', ', ', 'words', '.']
>>> re.split(r'\W*', '...words...')
['', '', 'w', 'o', 'r', 'd', 's', '', '']
>>> re.split(r'(\W*)', '...words...')
['', '...', '', '', 'w', '', 'o', '', 'r', '', 'd', '', 's', '...', '', '', '']
1 matches ‘foo2’ normally, but ‘foo1’ in
>>> re.split(r'(\W+)', '...words, words...')
['', '...', 'words', ', ', 'words', '...', '']
5 mode; searching for a single
>>> re.split(r'(\W+)', '...words, words...')
['', '...', 'words', ', ', 'words', '...', '']
6 in
>>> re.split(r'\b', 'Words, words, words.')
['', 'Words', ', ', 'words', ', ', 'words', '.']
>>> re.split(r'\W*', '...words...')
['', '', 'w', 'o', 'r', 'd', 's', '', '']
>>> re.split(r'(\W*)', '...words...')
['', '...', '', '', 'w', '', 'o', '', 'r', '', 'd', '', 's', '...', '', '', '']
4 will find two (empty) matches: one just before the newline, and one at the end of the string.

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

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

>>> re.split(r'\b', 'Words, words, words.')
['', 'Words', ', ', 'words', ', ', 'words', '.']
>>> re.split(r'\W*', '...words...')
['', '', 'w', 'o', 'r', 'd', 's', '', '']
>>> re.split(r'(\W*)', '...words...')
['', '...', '', '', 'w', '', 'o', '', 'r', '', 'd', '', 's', '...', '', '', '']
6 will match ‘a’, ‘ab’, or ‘a’ followed by any number of ‘b’s.

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

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

>>> re.split(r'\b', 'Words, words, words.')
['', 'Words', ', ', 'words', ', ', 'words', '.']
>>> re.split(r'\W*', '...words...')
['', '', 'w', 'o', 'r', 'd', 's', '', '']
>>> re.split(r'(\W*)', '...words...')
['', '...', '', '', 'w', '', 'o', '', 'r', '', 'd', '', 's', '...', '', '', '']
8 will match ‘a’ followed by any non-zero number of ‘b’s; it will not match just ‘a’.

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

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

>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
00 will match either ‘a’ or ‘ab’.

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

The

>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
04,
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
05, and
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
06 quantifiers are all greedy; they match as much text as possible. Sometimes this behaviour isn’t desired; if the RE
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
07 is matched against
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
08, it will match the entire string, and not just
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
09. Adding
>>> re.split(r'\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split(r'(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split(r'\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
7 after the quantifier 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(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
11 will match only
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
09.

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

Like the

>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
04,
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
05, and
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
06 quantifiers, those where
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
05 is appended also match as many times as possible. However, unlike the true greedy quantifiers, these do not allow back-tracking when the expression following it fails to match. These are known as possessive quantifiers. For example,
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
20 will match
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
21 because the
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
22 will match all 4
result = re.match(pattern, string)
7s, but, when the final
result = re.match(pattern, string)
7 is encountered, the expression is backtracked so that in the end the
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
22 ends up matching 3
result = re.match(pattern, string)
7s total, and the fourth
result = re.match(pattern, string)
7 is matched by the final
result = re.match(pattern, string)
7. However, when
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
29 is used to match
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
21, the
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
31 will match all 4
result = re.match(pattern, string)
7, but when the final
result = re.match(pattern, string)
7 fails to find any more characters to match, the expression cannot be backtracked and will thus fail to match.
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
34,
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
35 and
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
36 are equivalent to
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
37,
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
38 and
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
39 correspondingly.

New in version 3.11.

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

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(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
41 will match exactly six
result = re.match(pattern, string)
7 characters, but not five.

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

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(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
44 will match from 3 to 5
result = re.match(pattern, string)
7 characters. Omitting m specifies a lower bound of zero, and omitting n specifies an infinite upper bound. As an example,
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
46 will match
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
47 or a thousand
result = re.match(pattern, string)
7 characters followed by a
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
49, but not
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
50. The comma may not be omitted or the modifier would be confused with the previously described form.

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

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 quantifier. For example, on the 6-character string

>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
52,
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
44 will match 5
result = re.match(pattern, string)
7 characters, while
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
55 will only match 3 characters.

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

Causes the resulting RE to match from m to n repetitions of the preceding RE, attempting to match as many repetitions as possible without establishing any backtracking points. This is the possessive version of the quantifier above. For example, on the 6-character string

>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
52,
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
58 attempt to match 5
result = re.match(pattern, string)
7 characters, then, requiring 2 more
result = re.match(pattern, string)
7s, will need more characters than available and thus fail, while
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
61 will match with
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
44 capturing 5, then 4
result = re.match(pattern, string)
7s by backtracking and then the final 2
result = re.match(pattern, string)
7s are matched by the final
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
65 in the pattern.
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
66 is equivalent to
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
67.

New in version 3.11.

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

Either escapes special characters (permitting you to match characters like

>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
04,
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
06, 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(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
71

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

  • Characters can be listed individually, e.g.

    >>> m = re.search(r'(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    72 will match
    result = re.match(pattern, string)
    
    7,
    >>> m = re.search(r'(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    74, or
    >>> m = re.search(r'(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    75.

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

    >>> m = re.search(r'(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    76, for example
    >>> m = re.search(r'(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    77 will match any lowercase ASCII letter,
    >>> m = re.search(r'(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    78 will match all the two-digits numbers from
    >>> m = re.search(r'(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    79 to
    >>> m = re.search(r'(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    80, and
    >>> m = re.search(r'(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    81 will match any hexadecimal digit. If
    >>> m = re.search(r'(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    82 is escaped (e.g.
    >>> m = re.search(r'(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    83) or if it’s placed as the first or last character (e.g.
    >>> m = re.search(r'(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    84 or
    >>> m = re.search(r'(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    85), it will match a literal
    >>> m = re.search(r'(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    76.

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

    >>> m = re.search(r'(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    87 will match any of the literal characters
    >>> re.split(r'\W+', 'Words, words, words.')
    ['Words', 'words', 'words', '']
    >>> re.split(r'(\W+)', 'Words, words, words.')
    ['Words', ', ', 'words', ', ', 'words', '.', '']
    >>> re.split(r'\W+', 'Words, words, words.', 1)
    ['Words', 'words, words.']
    >>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
    ['0', '3', '9']
    
    4,
    >>> m = re.search(r'(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    05,
    >>> m = re.search(r'(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    04, or
    >>> m = re.search(r'(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    91.

  • Character classes such as

    >>> m = re.search(r'(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    92 or
    >>> m = re.search(r'(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    93 (defined below) are also accepted inside a set, although the characters they match depends on whether
    >>> m = re.search(r'(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    94 or
    >>> m = re.search(r'(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'
    
    95 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

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

  • To match a literal

    \a      \b      \f      \n
    \N      \r      \t      \u
    \U      \v      \x      \\
    
    02 inside a set, precede it with a backslash, or place it at the beginning of the set. For example, both
    \a      \b      \f      \n
    \N      \r      \t      \u
    \U      \v      \x      \\
    
    03 and
    \a      \b      \f      \n
    \N      \r      \t      \u
    \U      \v      \x      \\
    
    04 will both match a parenthesis.

  • Support of nested sets and set operations as in Unicode Technical Standard #18 might be added in the future. This would change the syntax, so to facilitate this change a

    \a      \b      \f      \n
    \N      \r      \t      \u
    \U      \v      \x      \\
    
    05 will be raised in ambiguous cases for the time being. That includes sets starting with a literal
    \a      \b      \f      \n
    \N      \r      \t      \u
    \U      \v      \x      \\
    
    06 or containing literal character sequences
    \a      \b      \f      \n
    \N      \r      \t      \u
    \U      \v      \x      \\
    
    07,
    \a      \b      \f      \n
    \N      \r      \t      \u
    \U      \v      \x      \\
    
    08,
    \a      \b      \f      \n
    \N      \r      \t      \u
    \U      \v      \x      \\
    
    09, and
    \a      \b      \f      \n
    \N      \r      \t      \u
    \U      \v      \x      \\
    
    10. To avoid a warning escape them with a backslash.

Changed in version 3.7:

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
05 is raised if a character set contains constructs that will change semantically in the future.

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
12

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
13, 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(r'\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split(r'(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split(r'\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
3 in this way. This can be used inside groups (see below) as well. As the target string is scanned, REs separated by
>>> re.split(r'\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split(r'(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split(r'\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
3 are tried from left to right. When one pattern completely matches, that branch is accepted. This means that once A matches, B will not be tested further, even if it would produce a longer overall match. In other words, the
>>> re.split(r'\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split(r'(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split(r'\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
3 operator is never greedy. To match a literal
>>> re.split(r'\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split(r'(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split(r'\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
3, use
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
18, or enclose it inside a character class, as in
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
19.

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
20

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

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
21 special sequence, described below. To match the literals
>>> re.split(r'\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split(r'(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split(r'\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
4 or
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
91, use
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
24 or
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
25, or enclose them inside a character class:
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
26,
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
27.

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
28

This is an extension notation (a

>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
06 following a
>>> re.split(r'\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split(r'(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split(r'\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
4 is not meaningful otherwise). The first character after the
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
06 determines what the meaning and further syntax of the construct is. Extensions usually do not create a new group;
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
32 is the only exception to this rule. Following are the currently supported extensions.

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
33

(One or more letters from the set

result = re.match(pattern, string)
7,
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
35,
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
36,
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
74,
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
38,
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
39,
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
40.) The group matches the empty string; the letters set the corresponding flags:
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
41 (ASCII-only matching),
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
42 (ignore case),
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
43 (locale dependent),
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
44 (multi-line),
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
45 (dot matches all),
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
46 (Unicode matching), and
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
47 (verbose), for the entire regular expression. (The flags are described in Module Contents.) This is useful if you wish to include the flags as part of the regular expression, instead of passing a flag argument to the
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
48 function. Flags should be used first in the expression string.

Changed in version 3.11: This construction can only be used at the start of the expression.

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
49

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.

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
50

(Zero or more letters from the set

result = re.match(pattern, string)
7,
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
35,
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
36,
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
74,
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
38,
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
39,
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
40, optionally followed by
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
76 followed by one or more letters from the
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
35,
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
74,
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
38,
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
40.) The letters set or remove the corresponding flags:
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
41 (ASCII-only matching),
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
42 (ignore case),
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
43 (locale dependent),
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
44 (multi-line),
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
45 (dot matches all),
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
46 (Unicode matching), and
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
47 (verbose), for the part of the expression. (The flags are described in Module Contents.)

The letters

result = re.match(pattern, string)
7,
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
36 and
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
39 are mutually exclusive when used as inline flags, so they can’t be combined or follow
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
76. Instead, when one of them appears in an inline group, it overrides the matching mode in the enclosing group. In Unicode patterns
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
74 switches to ASCII-only matching, and
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
75 switches to Unicode matching (default). In byte pattern
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
76 switches to locale depending matching, and
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
74 switches to ASCII-only matching (default). This override is only in effect for the narrow inline group, and the original matching mode is restored outside of the group.

New in version 3.6.

Changed in version 3.7: The letters

result = re.match(pattern, string)
7,
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
36 and
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
39 also can be used in a group.

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
81

Attempts to match

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
82 as if it was a separate regular expression, and if successful, continues to match the rest of the pattern following it. If the subsequent pattern fails to match, the stack can only be unwound to a point before the
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
81 because once exited, the expression, known as an atomic group, has thrown away all stack points within itself. Thus,
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
84 would never match anything because first the
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
85 would match all characters possible, then, having nothing left to match, the final
>>> re.split(r'(\W+)', '...words, words...')
['', '...', 'words', ', ', 'words', '...', '']
2 would fail to match. Since there are no stack points saved in the Atomic Group, and there is no stack point before it, the entire expression would thus fail to match.

New in version 3.11.

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
32

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

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
88 (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

  • \a      \b      \f      \n
    \N      \r      \t      \u
    \U      \v      \x      \\
    
    89 (as shown)

  • \a      \b      \f      \n
    \N      \r      \t      \u
    \U      \v      \x      \\
    
    90

when processing match object m

  • \a      \b      \f      \n
    \N      \r      \t      \u
    \U      \v      \x      \\
    
    91

  • \a      \b      \f      \n
    \N      \r      \t      \u
    \U      \v      \x      \\
    
    92 (etc.)

in a string passed to the repl argument of

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
93

  • \a      \b      \f      \n
    \N      \r      \t      \u
    \U      \v      \x      \\
    
    94

  • \a      \b      \f      \n
    \N      \r      \t      \u
    \U      \v      \x      \\
    
    95

  • \a      \b      \f      \n
    \N      \r      \t      \u
    \U      \v      \x      \\
    
    90

Deprecated since version 3.11: Group names containing non-ASCII characters in bytes patterns.

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
97

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

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
98

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

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
99

Matches if

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
82 matches next, but doesn’t consume any of the string. This is called a lookahead assertion. For example,
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
01 will match
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
02 only if it’s followed by
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
03.

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
04

Matches if

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
82 doesn’t match next. This is a negative lookahead assertion. For example,
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
06 will match
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
02 only if it’s not followed by
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
03.

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
09

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

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
82 that ends at the current position. This is called a positive lookbehind assertion.
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
11 will find a match in
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
12, 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
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
13 or
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
14 are allowed, but
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
22 and
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
16 are not. 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
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
17 function rather than the
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
18 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(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'

Changed in version 3.5: Added support for group references of fixed length.

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
19

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

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
82. This is called a negative lookbehind assertion. Similar to positive lookbehind assertions, the contained pattern must only match strings of some fixed length. Patterns which start with negative lookbehind assertions may match at the beginning of the string being searched.

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
21

Will try to match with

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
22 if the group with given id or name exists, and with
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
23 if it doesn’t.
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
23 is optional and can be omitted. For example,
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
25 is a poor email matching pattern, which will match with
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
26 as well as
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
27, but not with
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
28 nor
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
29.

Deprecated since version 3.11: Group id containing anything except ASCII digits.

The special sequences consist of

prog = re.compile(pattern)
result = prog.match(string)
4 and a character from the list below. If the ordinary character is not an ASCII digit or an ASCII letter, then the resulting RE will match the second character. For example,
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
31 matches the character
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
32.

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
21

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

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
34 matches
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
35 or
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
36, but not
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
37 (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
\N      \r      \t      \u
\U      \v      \x      \\
06 and
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
02 of a character class, all numeric escapes are treated as characters.

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
40

Matches only at the start of the string.

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
41

Matches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of word characters. Note that formally,

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
41 is defined as the boundary between a
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
92 and a
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
44 character (or vice versa), or between
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
92 and the beginning/end of the string. This means that
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
46 matches
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
47,
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
48,
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
49,
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
50 but not
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
51 or
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
52.

By default Unicode alphanumerics are the ones used in Unicode patterns, but this can be changed by using the

>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
94 flag. Word boundaries are determined by the current locale if the
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
95 flag is used. Inside a character range,
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
41 represents the backspace character, for compatibility with Python’s string literals.

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
56

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

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
57 matches
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
58,
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
59,
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
60, but not
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
61,
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
62, or
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
63.
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
56 is just the opposite of
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
41, so word characters in Unicode patterns are Unicode alphanumerics or the underscore, although this can be changed by using the
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
94 flag. Word boundaries are determined by the current locale if the
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
95 flag is used.

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
68For Unicode (str) patterns:

Matches any Unicode decimal digit (that is, any character in Unicode character category [Nd]). This includes

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
69, and also many other digit characters. If the
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
94 flag is used only
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
69 is matched.

For 8-bit (bytes) patterns:

Matches any decimal digit; this is equivalent to

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
69.

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
73

Matches any character which is not a decimal digit. This is the opposite of

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
68. If the
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
94 flag is used this becomes the equivalent of
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
76.

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
77For Unicode (str) patterns:

Matches Unicode whitespace characters (which includes

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
78, and also many other characters, for example the non-breaking spaces mandated by typography rules in many languages). If the
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
94 flag is used, only
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
78 is matched.

For 8-bit (bytes) patterns:

Matches characters considered whitespace in the ASCII character set; this is equivalent to

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
78.

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

Matches any character which is not a whitespace character. This is the opposite of

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
77. If the
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
94 flag is used this becomes the equivalent of
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
85.

>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
92For Unicode (str) patterns:

Matches Unicode word characters; this includes most characters that can be part of a word in any language, as well as numbers and the underscore. If the

>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
94 flag is used, only
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
88 is matched.

For 8-bit (bytes) patterns:

Matches characters considered alphanumeric in the ASCII character set; this is equivalent to

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
88. If the
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
95 flag is used, matches characters considered alphanumeric in the current locale and the underscore.

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
44

Matches any character which is not a word character. This is the opposite of

>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
92. If the
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
94 flag is used this becomes the equivalent of
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
94. If the
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
95 flag is used, matches characters which are neither alphanumeric in the current locale nor the underscore.

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
96

Matches only at the end of the string.

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

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\

(Note that

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
41 is used to represent word boundaries, and means “backspace” only inside character classes.)

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
98,
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
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 escape sequences are only recognized in Unicode patterns. In bytes patterns they are errors. Unknown escapes of ASCII letters are reserved for future use and treated as errors.

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.

Changed in version 3.3: The

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
98 and
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
99 escape sequences have been added.

Changed in version 3.6: Unknown escapes consisting of

prog = re.compile(pattern)
result = prog.match(string)
4 and an ASCII letter now are errors.

Changed in version 3.8: The

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
04 escape sequence has been added. As in string literals, it expands to the named Unicode character (e.g.
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
05).

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.

Flags¶

Changed in version 3.6: Flag constants are now instances of

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

class re.RegexFlag

An

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

New in version 3.11: - added to

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

re.Are.ASCII

Make

>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
92,
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
44,
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
41,
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
56,
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
68,
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
73,
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
77 and
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
93 perform ASCII-only matching instead of full Unicode matching. This is only meaningful for Unicode patterns, and is ignored for byte patterns. Corresponds to the inline flag
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
18.

Note that for backward compatibility, the

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
46 flag still exists (as well as its synonym
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
20 and its embedded counterpart
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
21), but these are redundant in Python 3 since matches are Unicode by default for strings (and Unicode matching isn’t allowed for bytes).

re.DEBUG

Display debug information about compiled expression. No corresponding inline flag.

re.Ire.IGNORECASE

Perform case-insensitive matching; expressions like

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 also match lowercase letters. Full Unicode matching (such as
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
23 matching
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
24) also works unless the
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
25 flag is used to disable non-ASCII matches. The current locale does not change the effect of this flag unless the
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
26 flag is also used. Corresponds to the inline flag
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
27.

Note that when the Unicode patterns

>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
77 or
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
22 are used in combination with the
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
30 flag, they will match the 52 ASCII letters and 4 additional non-ASCII letters: ‘İ’ (U+0130, Latin capital letter I with dot above), ‘ı’ (U+0131, Latin small letter dotless i), ‘ſ’ (U+017F, Latin small letter long s) and ‘K’ (U+212A, Kelvin sign). If the
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
94 flag is used, only letters ‘a’ to ‘z’ and ‘A’ to ‘Z’ are matched.

re.Lre.LOCALE

Make

>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
92,
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
44,
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
41,
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
56 and case-insensitive matching dependent on the current locale. This flag can be used only with bytes patterns. The use of this flag is discouraged as the locale mechanism is very unreliable, it only handles one “culture” at a time, and it only works with 8-bit locales. Unicode matching is already enabled by default in Python 3 for Unicode (str) patterns, and it is able to handle different locales/languages. Corresponds to the inline flag
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
36.

Changed in version 3.6:

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
26 can be used only with bytes patterns and is not compatible with
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
25.

Changed in version 3.7: Compiled regular expression objects with the

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
26 flag no longer depend on the locale at compile time. Only the locale at matching time affects the result of matching.

re.Mre.MULTILINE

When specified, the pattern character

>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
96 matches at the beginning of the string and at the beginning of each line (immediately following each newline); and the pattern character
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
32 matches at the end of the string and at the end of each line (immediately preceding each newline). By default,
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
96 matches only at the beginning of the string, and
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
32 only at the end of the string and immediately before the newline (if any) at the end of the string. Corresponds to the inline flag
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
44.

re.NOFLAG

Indicates no flag being applied, the value is

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
45. This flag may be used as a default value for a function keyword argument or as a base value that will be conditionally ORed with other flags. Example of use as a default value:

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)

New in version 3.11.

re.Sre.DOTALL

Make the

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
46 special character match any character at all, including a newline; without this flag,
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
46 will match anything except a newline. Corresponds to the inline flag
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
48.

re.Xre.VERBOSE

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

>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
01,
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
50 or
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
51. For example,
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
52 and
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
53 are not allowed. When a line contains a
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
54 that is not in a character class and is not preceded by an unescaped backslash, all characters from the leftmost such
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
54 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*")

Corresponds to the inline flag

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

Functions¶

re.compile(pattern, flags=0)

Compile a regular expression pattern into a regular expression object, which can be used for matching using its

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
18,
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
17 and other 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

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
12 operator).

The sequence

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

is equivalent to

result = re.match(pattern, string)

but using

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
48 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

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
48 and the module-level matching functions are cached, so programs that use only a few regular expressions at a time needn’t worry about compiling regular expressions.

re.search(pattern, string, flags=0)

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

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
62 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.

re.match(pattern, string, flags=0)

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

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
62 if the string does not match the pattern; note that this is different from a zero-length match.

Note that even in

>>> re.split(r'(\W+)', '...words, words...')
['', '...', 'words', ', ', 'words', '...', '']
5 mode,
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
65 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

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
17 instead (see also search() vs. match()).

re.fullmatch(pattern, string, flags=0)

If the whole string matches the regular expression pattern, return a corresponding match object. Return

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
62 if the string does not match the pattern; note that this is different from a zero-length match.

New in version 3.4.

re.split(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.

>>> re.split(r'\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split(r'(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split(r'\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(r'(\W+)', '...words, words...')
['', '...', 'words', ', ', 'words', '...', '']

That way, separator components are always found at the same relative indices within the result list.

Empty matches for the pattern split the string only when not adjacent to a previous empty match.

>>> re.split(r'\b', 'Words, words, words.')
['', 'Words', ', ', 'words', ', ', 'words', '.']
>>> re.split(r'\W*', '...words...')
['', '', 'w', 'o', 'r', 'd', 's', '', '']
>>> re.split(r'(\W*)', '...words...')
['', '...', '', '', 'w', '', 'o', '', 'r', '', 'd', '', 's', '...', '', '', '']

Changed in version 3.1: Added the optional flags argument.

Changed in version 3.7: Added support of splitting on a pattern that could match an empty string.

re.findall(pattern, string, flags=0)

Return all non-overlapping matches of pattern in string, as a list of strings or tuples. The string is scanned left-to-right, and matches are returned in the order found. Empty matches are included in the result.

The result depends on the number of capturing groups in the pattern. If there are no groups, return a list of strings matching the whole pattern. If there is exactly one group, return a list of strings matching that group. If multiple groups are present, return a list of tuples of strings matching the groups. Non-capturing groups do not affect the form of the result.

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

Changed in version 3.7: Non-empty matches can now start just after a previous empty match.

re.finditer(pattern, string, flags=0)

Return an iterator yielding match objects 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.

Changed in version 3.7: Non-empty matches can now start just after a previous empty match.

re.sub(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,

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
68 is converted to a single newline character,
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
69 is converted to a carriage return, and so forth. Unknown escapes of ASCII letters are reserved for future use and treated as errors. Other unknown escapes such as
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
70 are left alone. Backreferences, such as
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
71, are replaced with the substring matched by group 6 in the pattern. For example:

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

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(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
2

The pattern may be a string or a pattern 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 empty match, so

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

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

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
74 will use the substring matched by the group named
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
75, as defined by the
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
32 syntax.
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
77 uses the corresponding group number;
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
78 is therefore 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*")
79, but isn’t ambiguous in a replacement such as
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
80.
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
81 would be interpreted as a reference to group 20, not a reference to group 2 followed by the literal character
result = re.match(pattern, string)
8. The backreference
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
83 substitutes in the entire substring matched by the RE.

Changed in version 3.1: Added the optional flags argument.

Changed in version 3.5: Unmatched groups are replaced with an empty string.

Changed in version 3.6: Unknown escapes in pattern consisting of

prog = re.compile(pattern)
result = prog.match(string)
4 and an ASCII letter now are errors.

Changed in version 3.7: Unknown escapes in repl consisting of

prog = re.compile(pattern)
result = prog.match(string)
4 and an ASCII letter now are errors.

Changed in version 3.7: Empty matches for the pattern are replaced when adjacent to a previous non-empty match.

Deprecated since version 3.11: Group id containing anything except ASCII digits. Group names containing non-ASCII characters in bytes replacement strings.

re.subn(pattern, repl, string, count=0, flags=0)

Perform the same operation as

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

Changed in version 3.1: Added the optional flags argument.

Changed in version 3.5: Unmatched groups are replaced with an empty string.

re.escape(pattern)

Escape special characters in pattern. 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(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
3

This function must not be used for the replacement string in

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
86 and
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
89, only backslashes should be escaped. For example:

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

Changed in version 3.3: The

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

Changed in version 3.7: Only characters that can have special meaning in a regular expression are escaped. As a result,

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
91,
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
92,
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
93,
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
94,
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
95,
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
96,
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
97,
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
98,
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
99,
prog = re.compile(pattern)
result = prog.match(string)
00,
prog = re.compile(pattern)
result = prog.match(string)
01,
prog = re.compile(pattern)
result = prog.match(string)
02, and
prog = re.compile(pattern)
result = prog.match(string)
03 are no longer escaped.

re.purge()

Clear the regular expression cache.

Exceptions¶

exception re.error(msg, pattern=None, pos=None)

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. The error instance has the following additional attributes:

msg

The unformatted error message.

pattern

The regular expression pattern.

pos

The index in pattern where compilation failed (may be

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

lineno

The line corresponding to pos (may be

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

colno

The column corresponding to pos (may be

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

Changed in version 3.5: Added additional attributes.

Regular Expression Objects¶

Compiled regular expression objects support the following methods and attributes:

Pattern.search(string[, pos[, endpos]])

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

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
62 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

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
45. This is not completely equivalent to slicing the string; the
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
96 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

prog = re.compile(pattern)
result = prog.match(string)
10 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,
prog = re.compile(pattern)
result = prog.match(string)
11 is equivalent to
prog = re.compile(pattern)
result = prog.match(string)
12.

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

Pattern.match(string[, pos[, endpos]])

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

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
62 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

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
17 method.

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

If you want to locate a match anywhere in string, use

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
17 instead (see also search() vs. match()).

Pattern.fullmatch(string[, pos[, endpos]])

If the whole string matches this regular expression, return a corresponding match object. Return

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
62 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

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
17 method.

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

New in version 3.4.

Pattern.split(string, maxsplit=0)

Identical to the

prog = re.compile(pattern)
result = prog.match(string)
18 function, using the compiled pattern.

Pattern.findall(string[, pos[, endpos]])

Similar to the

prog = re.compile(pattern)
result = prog.match(string)
19 function, using the compiled pattern, but also accepts optional pos and endpos parameters that limit the search region like for
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
17.

Pattern.finditer(string[, pos[, endpos]])

Similar to the

prog = re.compile(pattern)
result = prog.match(string)
21 function, using the compiled pattern, but also accepts optional pos and endpos parameters that limit the search region like for
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
17.

Pattern.sub(repl, string, count=0)

Identical to the

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

Pattern.subn(repl, string, count=0)

Identical to the

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

Pattern.flags

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

prog = re.compile(pattern)
result = prog.match(string)
25, any
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
28 inline flags in the pattern, and implicit flags such as
prog = re.compile(pattern)
result = prog.match(string)
27 if the pattern is a Unicode string.

Pattern.groups

The number of capturing groups in the pattern.

Pattern.groupindex

A dictionary mapping any symbolic group names defined by

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

Pattern.pattern

The pattern string from which the pattern object was compiled.

Changed in version 3.7: Added support of

prog = re.compile(pattern)
result = prog.match(string)
29 and
prog = re.compile(pattern)
result = prog.match(string)
30. Compiled regular expression objects are considered atomic.

Match Objects¶

Match objects always have a boolean value of

prog = re.compile(pattern)
result = prog.match(string)
31. Since
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
18 and
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
17 return
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
62 when there is no match, you can test whether there was a match with a simple
prog = re.compile(pattern)
result = prog.match(string)
35 statement:

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

Match objects support the following methods and attributes:

Match.expand(template)

Return the string obtained by doing backslash substitution on the template string template, as done by the

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
86 method. Escapes such as
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
68 are converted to the appropriate characters, and numeric backreferences (
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
90,
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
79) and named backreferences (
\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
95,
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
74) are replaced by the contents of the corresponding group.

Changed in version 3.5: Unmatched groups are replaced with an empty string.

Match.group([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

prog = re.compile(pattern)
result = prog.match(string)
42 exception is raised. If a group is contained in a part of the pattern that did not match, the corresponding result is
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
62. If a group is contained in a part of the pattern that matched multiple times, the last match is returned.

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

If the regular expression uses the

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
32 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
prog = re.compile(pattern)
result = prog.match(string)
42 exception is raised.

A moderately complicated example:

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
0

Named groups can also be referred to by their index:

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
1

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

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
2

Match.__getitem__(g)

This is identical to

prog = re.compile(pattern)
result = prog.match(string)
46. This allows easier access to an individual group from a match:

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
3

Named groups are supported as well:

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
4

New in version 3.6.

Match.groups(default=None)

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

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

For example:

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
5

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

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
62 unless the default argument is given:

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
6

Match.groupdict(default=None)

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

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

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
7

Match.start([group])Match.end([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

prog = re.compile(pattern)
result = prog.match(string)
50 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
prog = re.compile(pattern)
result = prog.match(string)
46) is

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
8

Note that

prog = re.compile(pattern)
result = prog.match(string)
52 will equal
prog = re.compile(pattern)
result = prog.match(string)
53 if group matched a null string. For example, after
prog = re.compile(pattern)
result = prog.match(string)
54,
prog = re.compile(pattern)
result = prog.match(string)
55 is 1,
prog = re.compile(pattern)
result = prog.match(string)
56 is 2,
prog = re.compile(pattern)
result = prog.match(string)
57 and
prog = re.compile(pattern)
result = prog.match(string)
58 are both 2, and
prog = re.compile(pattern)
result = prog.match(string)
59 raises an
prog = re.compile(pattern)
result = prog.match(string)
42 exception.

An example that will remove remove_this from email addresses:

\a      \b      \f      \n
\N      \r      \t      \u
\U      \v      \x      \\
9

Match.span([group])

For a match m, return the 2-tuple

prog = re.compile(pattern)
result = prog.match(string)
61. Note that if group did not contribute to the match, this is
prog = re.compile(pattern)
result = prog.match(string)
62. group defaults to zero, the entire match.

Match.pos

The value of pos which was passed to the

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
17 or
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
18 method of a regex object. This is the index into the string at which the RE engine started looking for a match.

Match.endpos

The value of endpos which was passed to the

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
17 or
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
18 method of a regex object. This is the index into the string beyond which the RE engine will not go.

Match.lastindex

The integer index of the last matched capturing group, or

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
62 if no group was matched at all. For example, the expressions
prog = re.compile(pattern)
result = prog.match(string)
68,
prog = re.compile(pattern)
result = prog.match(string)
69, and
prog = re.compile(pattern)
result = prog.match(string)
70 will have
prog = re.compile(pattern)
result = prog.match(string)
71 if applied to the string
prog = re.compile(pattern)
result = prog.match(string)
72, while the expression
prog = re.compile(pattern)
result = prog.match(string)
73 will have
prog = re.compile(pattern)
result = prog.match(string)
74, if applied to the same string.

Match.lastgroup

The name of the last matched capturing group, or

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
62 if the group didn’t have a name, or if no group was matched at all.

Match.re

The regular expression object whose

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
18 or
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
17 method produced this match instance.

Match.string

The string passed to

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
18 or
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
17.

Changed in version 3.7: Added support of

prog = re.compile(pattern)
result = prog.match(string)
29 and
prog = re.compile(pattern)
result = prog.match(string)
30. Match objects are considered atomic.

Regular Expression Examples¶

Checking for a Pair¶

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

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
0

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:

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
1

That last hand,

prog = re.compile(pattern)
result = prog.match(string)
82, contained a pair, or two of the same valued cards. To match this with a regular expression, one could use backreferences as such:

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
2

To find out what card the pair consists of, one could use the

prog = re.compile(pattern)
result = prog.match(string)
83 method of the match object in the following manner:

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
3

Simulating scanf()¶

Python does not currently have an equivalent to

prog = re.compile(pattern)
result = prog.match(string)
84. Regular expressions are generally more powerful, though also more verbose, than
prog = re.compile(pattern)
result = prog.match(string)
84 format strings. The table below offers some more-or-less equivalent mappings between
prog = re.compile(pattern)
result = prog.match(string)
84 format tokens and regular expressions.

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

Regular Expression

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

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

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

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

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

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

prog = re.compile(pattern)
result = prog.match(string)
94,
prog = re.compile(pattern)
result = prog.match(string)
95,
prog = re.compile(pattern)
result = prog.match(string)
96,
prog = re.compile(pattern)
result = prog.match(string)
97

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

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

result = re.match(pattern, string)
00

result = re.match(pattern, string)
01

result = re.match(pattern, string)
02

result = re.match(pattern, string)
03

result = re.match(pattern, string)
04

result = re.match(pattern, string)
05

result = re.match(pattern, string)
06

result = re.match(pattern, string)
07,
result = re.match(pattern, string)
08

result = re.match(pattern, string)
09

To extract the filename and numbers from a string like

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
4

you would use a

prog = re.compile(pattern)
result = prog.match(string)
84 format like

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
5

The equivalent regular expression would be

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
6

search() vs. match()¶

Python offers two different primitive operations based on 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*")
65 checks for a match only at the beginning of the string, while
result = re.match(pattern, string)
12 checks for a match anywhere in the string (this is what Perl does by default).

For example:

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
7

Regular expressions beginning with

>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
96 can be used with
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
17 to restrict the match at the beginning of the string:

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
8

Note however that in

>>> re.split(r'(\W+)', '...words, words...')
['', '...', 'words', ', ', 'words', '...', '']
5 mode
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
18 only matches at the beginning of the string, whereas using
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
17 with a regular expression beginning with
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
96 will match at the beginning of each line.

def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
9

Making a Phonebook¶

prog = re.compile(pattern)
result = prog.match(string)
18 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

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

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:

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

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

result = re.match(pattern, string)
20 parameter of
prog = re.compile(pattern)
result = prog.match(string)
18 because the address has spaces, our splitting pattern, in it:

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

The

result = re.match(pattern, string)
22 pattern matches the colon after the last name, so that it does not occur in the result list. With a
result = re.match(pattern, string)
20 of
result = re.match(pattern, string)
24, we could separate the house number from the street name:

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

Text Munging¶

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
86 replaces every occurrence of a pattern with a string or the result of a function. This example demonstrates using
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
86 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:

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

Finding all Adverbs¶

prog = re.compile(pattern)
result = prog.match(string)
19 matches all occurrences of a pattern, not just the first one as
def myfunc(text, flag=re.NOFLAG):
    return re.match(text, flag)
17 does. For example, if a writer wanted to find all of the adverbs in some text, they might use
prog = re.compile(pattern)
result = prog.match(string)
19 in the following manner:

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

Finding all Adverbs and their Positions¶

If one wants more information about all matches of a pattern than the matched text,

prog = re.compile(pattern)
result = prog.match(string)
21 is useful as it provides match objects 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
prog = re.compile(pattern)
result = prog.match(string)
21 in the following manner:

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

Raw String Notation¶

Raw string notation (

result = re.match(pattern, string)
32) keeps regular expressions sane. Without it, every backslash (
prog = re.compile(pattern)
result = prog.match(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:

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

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

result = re.match(pattern, string)
34. Without raw string notation, one must use
result = re.match(pattern, string)
35, making the following lines of code functionally identical:

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

Writing a Tokenizer¶

A tokenizer or scanner analyzes a string to categorize groups of characters. This is a useful first step in writing a compiler or interpreter.

The text categories are specified with regular expressions. The technique is to combine those into a single master regular expression and to loop over successive matches:

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

The tokenizer produces the following output:

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

Frie09

Friedl, Jeffrey. Mastering Regular Expressions. 3rd ed., O’Reilly Media, 2009. The third edition of the book no longer covers Python at all, but the first edition covered writing good regular expression patterns in great detail.