Yurttas/PL/SL/python/docs/core-python-programming/doc/20/lib/matching-searching.html

Revision as of 19:45, 7 November 2013 by MassBot1 (talk | contribs) (Created page with "<div class="navigation"> {| width="100%" cellspacing="2" align="center" | yurttas/PL/SL/python/docs/core-python-programming/doc/20/lib/re-syntax.html|[[Image:yurttas_PL...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)


4.2.2 Matching vs. Searching

Python offers two different primitive operations based on regular expressions: match and search. If you are accustomed to Perl's semantics, the search operation is what you're looking for. See the search() function and corresponding method of compiled regular expression objects.

Note that match may differ from search using a regular expression beginning with "^": "^" matches only at the start of the string, or in MULTILINE mode also immediately following a newline. The ``match'' operation succeeds only if the pattern matches at the start of the string regardless of mode, or at the starting position given by the optional pos argument regardless of whether a newline precedes it.

re.compile("a").match("ba", 1)           # succeeds
re.compile("^a").search("ba", 1)         # fails; 'a' not at start
re.compile("^a").search("\na", 1)        # fails; 'a' not at start
re.compile("^a", re.M).search("\na", 1)  # succeeds
re.compile("^a", re.M).search("ba", 1)   # fails; no preceding \n

See About this document... for information on suggesting changes.