Next / Previous / Contents / TCC Help System / NM Tech homepage

28.5.2. Functions in the re module

There are two ways to match regular expressions with the re module. Assuming you import the module with import re, you can test whether a regular expression r matches a string s with the construct:


However, if you will be matching the same regular expression many times, the performance will be better if you compile the regular expression like this:


The re.compile() function returns a compiled regular expression object. You can then check a string s for matching by using the .match(s) method on that object.

Here are the functions in module re:


Compile regular expression r. This function returns a compiled regular expression object; see Section 28.5.3, “Compiled regular expression objects”. To get case-insensitive matching, use re.I as the f argument. There are other flags that may be passed to the f argument; see the Python Library Reference.


If r matches the start of string s, return a MatchObject (see below), otherwise return None.


Like the match() method, but matches r anywhere in s, not just at the beginning.


Splits string s into pieces where pattern r occurs. If r does not contain groups, returns a list of the parts of s that match r, in order. If r contains groups, returns a list containing all the characters from s, with parts matching r in separate elements from the non-matching parts. If the m argument is given, it specifies the maximum number of pieces that will be split, and the leftovers will be returned as an extra string at the end of the list.


Replace the leftmost non-overlapping parts of s that match r using R; returns s if there is no match. The R argument can be a string or a function that takes one MatchObject argument and returns the string to be substituted. If the c argument is supplied (defaulting to 0), no more than c replacements are done, where a value of 0 means do them all.