re module - cannot make expression

Steven Bethard steven.bethard at gmail.com
Mon Jan 31 11:36:38 EST 2005


Laszlo Zsolt Nagy wrote:
> I would like to match strings not beginning with '/webalizer'. How can I 
> do this?

Are you sure you need a regular expression?  The str.startswith method 
is what I would normally use to solve this kind of problem:

py> lst = ['aax', 'abx', 'acx', 'aay', 'aby', 'acy']
py> [s for s in lst if not s.startswith('ab')]
['aax', 'acx', 'aay', 'acy']

If you do need a regular expression, Steve Holden's suggestion about 
negative lookahead assertions is the right way to go:

py> s = 'aaxabxacxaayabyacy'
py> re.compile(r'(?!ab).{2}[xy]+').findall(s)
['aax', 'acx', 'aay', 'acy']

Steve



More information about the Python-list mailing list