Regex match back to a period or start of string

Viewed 2627

I'd like to match a word, then get everything before it up to the first occurance of a period or the start of the string.

For example, given this string and searching for the word "regex":

s = 'Do not match this. Or this. Or this either. I like regex. It is hard, but regex is also rewarding.'

It should return:

>> I like regex.
>> It is hard, but regex is also rewarding.

I'm trying to get my head around look-aheads and look-behinds, but (it seems) you can't easily look back until you hit something, only if it's immediately next to your pattern. I can get pretty close with this:

pattern = re.compile(r'(?:(?<=\.)|(?<=^))(.*?regex.*?\.)')

But it gives me the first period, then everything up to "regex":

>> Do not match this. Or this. Or this either. I like regex.  # no!
>> It is hard, but regex is also rewarding.                   # correct
1 Answers
Related