re help

Andrew M. Kuchling akuchlin at mems-exchange.org
Thu Oct 21 16:33:43 EDT 1999


mehta at mama.indstate.edu writes:
> how can I specify not to match strings like
>  donot match "one" | "two" | "three"
>   (one|two|three) could match any string as one or two or three
> but I want them not to matched at that position.

Use a negative lookahead assertion, which looks like (?! ... ).  It
lets the rest of the match continue only if the contents (the ...) do
not match at the current position.

>>> import re
>>> p = re.compile('(?!one|two|three)')
>>> print p.match( 'one')
None
>>> print p.match( 'two')
None
>>> print p.match( 'three')
None
>>> print p.match( 'four')
<re.MatchObject instance at f2f88>

In the last example, the resulting match extends from 0 to 0;
assertions always have zero width.

-- 
A.M. Kuchling			http://starship.python.net/crew/amk/
So what was I to do? To go backward was base: to go forward an adventure into
splendour and terror. But it was forward I must go.
    -- Robertson Davies, _The Rebel Angels_






More information about the Python-list mailing list