Using regex to remove sentence after occurrence of key phrase python

Viewed 50

I am looking for a regex solution to remove any words in the rest of the sentence after the occurrence of a key phrase.

Example

sentence = "The weather forecast for today is mostly sunny. The forecast for tomorrow will be rainy. The rest of the week..."

Key_phrase = "for tomorrow"

Desired output = "The weather forecast for today is mostly sunny. The forecast. The rest of the week..."

Attempt

head, sep, tail = sentence.partition(key_phrase)
print(head)

My idea is to first split the string into sentences, apply the above technique and then join the results. However, I feel like there must be a more elegant way to do this with regex?

Thanks for the help

2 Answers

Using re.sub

Ex:

sentence = "The weather forecast for today is mostly sunny. The forecast for tomorrow will be rainy. The rest of the week..."
key_phrase = "for tomorrow"
print(re.sub(fr"({key_phrase}.*?)(?=\.)", "", sentence))

Output

The weather forecast for today is mostly sunny. The forecast . The rest of the week...

Use

re.sub(fr"{re.escape(key_phrase)}[^.]*", "", sentence)

See regex proof.

EXPLANATION

--------------------------------------------------------------------------------
  for                      'for'
--------------------------------------------------------------------------------
  \                        ' '
--------------------------------------------------------------------------------
  tomorrow                 'tomorrow'
--------------------------------------------------------------------------------
  [^.]*                    any character except: '.' (0 or more times
                           (matching the most amount possible))

See Python proof:

import re
sentence = "The weather forecast for today is mostly sunny. The forecast for tomorrow will be rainy. The rest of the week..."
key_phrase = "for tomorrow"
print(re.sub(fr"{re.escape(key_phrase)}[^.]*", "", sentence))

Results: The weather forecast for today is mostly sunny. The forecast . The rest of the week...

Related