[Tutor] regular expression question

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Wed Mar 9 03:42:17 CET 2005

On Tue, 8 Mar 2005, Mike Hall wrote:

> Yes, my existing regex is using a look behind assertion:
> (?<=dog)
> ...it's also checking the existence of "Cat":
> (?!Cat)
> ...what I'm stuck on is how to essentially use a lookbehind on "Cat",
> but only if it exists.

Hi Mike,

[Note: Please do a reply-to-all next time, so that everyone can help you.]

Regular expressions are a little evil at times; here's what I think you're
thinking of:

>>> import re
>>> pattern = re.compile(r"""dog(?!cat)
...                    | (?<=dogcat)""", re.VERBOSE)
>>> pattern.match('dogman').start()
>>> pattern.search('dogcatcher').start()
>>> pattern.search('dogman').start()
>>> pattern.search('catwoman')

but I can't be sure without seeing some of the examples you'd like the
regular expression to match against.

Best of wishes to you!

More information about the Tutor mailing list