Use only re.search()

I am over and over again looking for the difference between re.match() and re.search(), I just can’t remember (it’s a bit like PHP’s parameter twisting, see 1, 2). The documentation chapter “Matching vs Searching” does not really help either, it only confuses me. Ok, it says that re.match() kind of magically adds a “^” up front of the given pattern. But where the heck is the second parameter (the “1″), they use in their examples, defined as a pos argument? Also this doc says, in the next chapter, the last parameter contains the flags (e.g. re.I re.M, etc.). I was even diving into the re, sre source code, but couldn’t find this match() method either. And help(_sre.SRE_Pattern.match) also fails (_sre.SRE_Pattern is the type of what re.compile() returns).

Ok, enough confusion, at least for me. I just have to write down which method only to use, from now on!
Only use re.search() it searches the entire string and has no special behaviour, it just applies the pattern onto the entire string, as I am used to it from the various preg_* functions.

1 Comment »

  1. Steve Holden said,

    March 3, 2006 at 9:02 am

    Think of it this way: search() will look for a match starting anywhere in a string, while match() will look starting only at a fixed position. This fixed position is usually the start of the string (hence the remark about the “implicit ^”) but can be varied by changing pos.

RSS feed for comments on this post · TrackBack URL

Leave a Comment