Why re.match()?

Duncan Booth duncan.booth at invalid.invalid
Wed Jul 1 20:52:34 CEST 2009


kj <no.email at please.post> wrote:

> 
> 
> For a recovering Perl-head like me it is difficult to understand
> why Python's re module offers both match and search.  Why not just
> use search with a beginning-of-string anchor?  I find it particularly
> puzzling because I have this (possibly mistaken) idea that the
> Python design philosophy tends towards minimalism, a sort of Occam's
> razor, when it comes to language entities; i.e. having re.match
> along with re.search seems to me like an "unnecessary multiplication
> of entities".  What am I missing?
> 
RTFM?

http://docs.python.org/library/re.html#matching-vs-searching says:

> Note that match may differ from search even when 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. 

So, for example:

>>> re.compile("c").match("abcdef", 2)
<_sre.SRE_Match object at 0x0000000002C09B90>
>>> re.compile("^c").search("abcdef", 2)
>>>

The ^ anchors you to the start of the string (or start of line in multiline 
mode) even if you specify a non-zero position. The match method just tells 
you if the pattern matches at the specified starting position regardless of 
whether it is the start of the string.




More information about the Python-list mailing list