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 - [email protected] http://mail.python.org/mailman/listinfo/tutor
