Regular expressions vs find?

Andrew Kuchling akuchlin at mems-exchange.org
Sun Jun 18 11:48:19 EDT 2000


"William Dandreta" <wjdandreta at worldnet.att.net> writes:
> I recently read a message that suggested that using regular expressions
> might be faster than the find function. I've heard the term regular
> expression used from time to time but I don't know what it means. Could
> someone give me a simple explanation?

Regular expressions are a mini-language for defining a certain set of
strings; the re module then takes a regular expression and tells you
if a given string matches the expression.  For example, [abc] means
'a', 'b', or 'c'; \bA.*?\b means a word beginning with 'A' (\b is a
special sequence meaning "match a word boundary").  As you can see,
regular expressions are concise but can easily be obscure.

Regular expressions will practically never be faster than a simple
string.find, so if you're searching for a fixed string, don't use
regular expressions; their extra expressive power costs you in
performance.  But they can do things that aren't possible with the
string module alone, and would require several lines of Python code 
to implement.

Consult the Library Reference, or the Regular Expression HOWTO for
more info.  (http://www.python.org/doc/current/lib/module-re.html,
http://www.python.org/doc/howto/regex/)

--amk



More information about the Python-list mailing list