First, thanks for the response. Using your re:

my_re = re.compile(r'(dog)(cat)?')

...I seem to simply be matching the pattern "Dog". Example:

>>> str1 = "The dog chased the car"
>>> str2 = "The dog cat parade was under way"
>>> x1 = re.compile(r'(dog)(cat)?')
>>> rep1 = x1.sub("REPLACE", str1)
>>> rep2 = x2.sub("REPLACE", str2)
>>> print rep1
The REPLACE chased the car
>>> print rep2
The REPLACE cat parade was under way


...what I'm looking for is a match for the position in front of "Cat", should it exist.




On Mar 8, 2005, at 5:54 PM, Sean Perry wrote:

Mike Hall wrote:
I'd like to get a match for a position in a string preceded by a specified word (let's call it "Dog"), unless that spot in the string (after "Dog") is directly followed by a specific word(let's say "Cat"), in which case I want my match to occur directly after "Cat", and not "Dog."
I can easily get the spot after "Dog," and I can also get it to ignore this spot if "Dog" is followed by "Cat." But what I'm having trouble with is how to match the spot after "Cat" if this word does indeed exist in the string.

. >>> import re
. >>> my_re = re.compile(r'(dog)(cat)?') # the ? means "find one or zero of these, in other words cat is optional.
. >>> m = my_re.search("This is a nice dog is it not?")
. >>> dir(m)
['__copy__', '__deepcopy__', 'end', 'expand', 'group', 'groupdict', 'groups', 'span', 'start']
. >>> m.span()
(15, 18)
. >>> m = my_re.search("This is a nice dogcat is it not?")
. >>> m.span()
(15, 21)


If m is None then no match was found. span returns the locations in the string where the match occured. So in the dogcat sentence the last char is 21.

. >>> "This is a nice dogcat is it not?"[21:]
' is it not?'

Hope that helps.
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


_______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor

Reply via email to