[Tutor] String matching

Jacob S. keridee at jayco.net
Fri Nov 26 18:56:55 CET 2004


Hi Bernard!

> Hello,
>
> I'm a little bit confused about the match/search methods of the string
> module for regular expressions. I have looked the regular expression doc
> and I can't that one simple answer.
>
> So please excuse the basiqueness of my question, as I am used with the
> .match method of JScript and it kind of matches anything....
>
> Let say I have this string:
>
>  >>> import re
>  >>> mystring = 'helloworldmynameisbernardlebel'
>
> Now I wish to attempt a match with 'bernard'.
>
>  >>> if not re.compile( 'bernard' ).match( mystring ) == None:
> ... print 'success'

First, you are printinting redundant code here. You are using double
negatives.
You first check to see if re.compile('bernard').match(mystring) registers
false, if it is false the expression registers true. Then you check to see
if that expression registers false. So really
the equivalent expression is

if re.compile('bernard').match(mystring):
    print 'success'

However, I don't think that solves your problem.
> Well, nothing gets printed. Could anyone tell me how to achieve that
> simple type of matching?

Re expressions are a little different from JScript. The match method only
matches equivalent strings. (Or it only does in this case.) Instead, you
want
to use the search method. Oh, and by the way, if you're going to compile the
expression without assigning it to a variable, you might use the re methods
instead
of the re pattern methods. IOW, use this code instead...

import re
mystring = 'helloworldmynameisbernardlebel'
if re.search('bernard',mystring):
    print 'success'

The documentation for the re methods are hidden, IMHO. You can find them
by typing in 'search() (in module re)' in the index and that should take you
right to it.
That page contains explanations for all of the re methods.

Good luck,
Jacob Schmidt



More information about the Tutor mailing list