[Tutor] String matching
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Fri Nov 26 21:26:00 CET 2004
> > >>> mystring = 'helloworldmynameisbernardlebel'
> >
> > Now I wish to attempt a match with 'bernard'.
> >
> > >>> if not re.compile( 'bernard' ).match( mystring ) == None:
> > ... print 'success'
> >
> > Well, nothing gets printed. Could anyone tell me how to achieve that
> > simple type of matching?
>
> You need to use search(), not match(). match() tries to match the
> pattern to the beginning of the string. IOW, in your case it tries to
> see if mystring begins with "bernard".
Hi Bernard,
If it helps, imagine that match() always puts a beginning anchor '^' at
the beginning of the pattern, and you'll see the difference between
match() and search().
(I'm lying in a small way: that's not exactly how match() works, but it's
close... *grin*)
There's also a brief discussion about it in the documentation:
http://www.python.org/doc/lib/matching-searching.html
which tries to show more formally why we have both match() and search().
Good luck to you!
More information about the Tutor
mailing list