regex's
Tim Hochberg
tim.hochberg at ieee.org
Tue Jul 4 21:47:49 EDT 2000
chibaA at TinterlogD.Tcom writes:
> Hi... I'm having a bit of a brain-tease... I have the following code
> (example):
>
> import re
>
> str = '123'
> if re.compile('1').match(str):
> print "matched 1"
> if re.compile('2').match(str):
> print "matched 2"
> if re.compile('3').match(str):
> print "matched 3"
>
> -------------------
>
> I would think that this code would print 'matched 1 matched 2 matched
> 3'... But in this case, it would only printed "matched 1". Any
> reasons? Is there any way to have it print all three (since the
> conditions seem to be true)?
re.match matches from the beginning of the string (e.g.,
re.compile('2').match(str) will only match strings starting with
'2'. What you want is re.search. For example:
#....
if re.compile('2').search(str):
# ...
You could also use:
#....
if re.search('2', str):
# ...
However, the former will be faster if you reuse the regular
expression since you can compile it once and reuse the compiled
version.
-tim
> Thanks in advance!
>
> kc.
More information about the Python-list
mailing list