re.match question
Andrew Kuchling
akuchlin at mems-exchange.org
Thu Oct 5 15:44:58 EDT 2000
Dan Schmidt <dfan at harmonixmusic.com> writes:
> As I was about to send this, I looked at the Perl regexp
> documentation, and it actually mentions your exact case:
>
> `/foo(?!bar)/' matches any occurrence of "foo" that isn't followed
> by "bar". Note however that lookahead and lookbehind are NOT the
> same thing. You cannot use this for lookbehind: `/(?!foo)bar/' will
Note that lookbehind is in both Perl 5.005 and in Python 2.0. So the
original poster's:
> | re.match('^.*?(?!Foo)Bar$', word)
could be written in Python 2.0 as:
p = re.compile('(?<!Foo)Bar$')
m = p.search('xxxBar')
print m and m.span()
m = p.search('xxxFooBar')
print m and m.span()
This prints (3,6) as the match for the first search() call, and None
for the second since it fails. Note that the lookbehind is a
zero-width assertion, so in the first example, the match extends from
characters 3 to 6 (the 'Bar' in 'xxxBar').
--
A.M. Kuchling http://starship.python.net/crew/amk/
Let us overthrow the totems, break the taboos. Or better, let us consider them
cancelled. Coldly, let us be intelligent.
-- Pierre Trudeau, "Politique fonctionnelle" (1950)
More information about the Python-list
mailing list