文档介绍:Regular Expression HOWTO
Regular Expression HOWTO
. Kuchling
******@
Abstract:
This document is an introductory tutorial to using regular expressions in Python with
the re module. It provides a gentler introduction than the corresponding section in the
Library Reference.
This document is available from hon/howto.
Contents
· 1 Introduction
· 2 Simple Patterns
o Matching Characters
o Repeating Things
· 3 Using Regular Expressions
o Regular Expressions
o The Backslash Plague
o Performing Matches
o Module-Level Functions
o Flags
· 4 More Pattern Power
o More Metacharacters
o Grouping
o Non-capturing and Named Groups
o Lookahead Assertions
· 5 Modifying Strings
o Splitting Strings
o Search and Replace
· mon Problems
o Use String Methods
o match() versus search()
o Greedy versus Non-Greedy
o Not Using
· 7 Feedback
· About this document ...
1 Introduction
The re module was added in Python , and provides Perl-style regular expression
patterns. Earlier versions of Python came with the regex module, which provides
Emacs-style patterns. Emacs-style patterns are slightly less readable and don't provide
as many features, so there's not much reason to use the regex module when writing
new code, though you might encounter old code that uses it.
Regular expressions (or REs) are essentially a tiny, highly specialized programming
language embedded inside Python and made available through the re module. Using
this little language, you specify the rules for the set of possible strings that you want
to match; this set might contain English sentences, or e-mail addresses, or TeX
commands, or anything you like. You can then ask questions such as ``Does this
string match the pattern?'', or ``Is there a match for the pattern anywhere in this
string?''. You can a