regex search with a space as the fist character

Jack Norton jack at 0x6a.com
Thu Sep 17 13:25:49 EDT 2009


Diez B. Roggisch wrote:
> Daniel Santos schrieb:
>> Hello,
>>
>>>>> print re.compile('u ').search(" u box2", 1)
>> <_sre.SRE_Match object at 0x7ff1d918>
>>>>> print re.compile(' u ').search(" u box2", 1)
>> None
>>
>>
>> Why ?
>
> because you start searching at the offset 1, which means you try to 
> find " u " in "u box2" - and that's not found.
>
> Diez
Couldn't you also just do:
re.compile('^\su')?  That would match only if the first character is a
space and the second a 'u'.
I mean, I like to try and have the regexp do it all, instead of forcing
an index, not to mention trying to find the most specific regexp that
works(least generic -- I don't want any false positives).  I also do
_not_ like having spaces in the regexp itself.  If I need more than one
space I'll use '\s*' or '\s+'.
Also, whats the point of compiling the regexp if you use it only once?

-Jack




More information about the Python-list mailing list