faqts : Computers : Programming : Languages : Python : Snippets : Regular Expressions

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

3 of 3 people (100%) answered Yes
Recently 2 of 2 people (100%) answered Yes

Entry

*Not* matching strings ;-) (was: re help)

Jul 5th, 2000 10:01
Nathan Wallace, unknown unknown, Hans Nowak, Snippet 195, Andrew Kuchling


"""
Packages: text.regular_expressions
"""
"""
> 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.
"""