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 matches a string r with the
construct:
s
re.match(r,s)
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:
re.compile(r)
The re.compile() function returns a
compiled regular expression object. You can then check
a string s for matching by using the .match( method
on that object.
s)
Here are the functions in module re:
compile(r[,f])
Compile regular expression . This function returns
a compiled regular expression object; see Section 28.5.3, “Compiled regular expression objects”. To get
case-insensitive matching, use rre.I as the argument. There are other flags that
may be passed to the f argument; see the
Python Library Reference.
f
match(r,s[,f])
If
matches the start of string r, return a sMatchObject (see below), otherwise return None.
search(r,s[,f])
Like the match() method, but matches
anywhere
in r, not
just at the beginning.
s
split(r,s[,maxsplit=m])
Splits string into pieces where pattern s occurs. If
r does not
contain groups, returns a list of the parts of r that match
s, in
order. If r contains groups, returns a list containing all the
characters from r, with parts matching s in separate elements from
the non-matching parts. If the r 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.
m
sub(r,R,s[,count=c])
Replace the leftmost non-overlapping parts of that match
s using
r; returns
R if there
is no match. The s argument can be a string or a function that
takes one RMatchObject argument and returns the
string to be substituted. If the argument is supplied
(defaulting to 0), no more than c replacements are done, where
a value of 0 means do them all.
c