Regular Expression: match word in a blank of a sentence

Question:

I have the following line:

I _ foo and _

I want to match anything (case insensitive) that matches the text and has a words that replace the underscores e. g.

I want foo and bar
I implemented foo and foo
i use Foo and bar

So in this case I want to get the whole sentences back: ["I want foo and bar", "I implemented foo and foo", "i use Foo and bar"]

To be honest, I don’t have any idea.

Asked By: kabow20

||

Answers:

import re

strings = [
    "I want foo and bar",
    "I implemented foo and foo",
    "i use Foo and bar"
]

for string in strings:
    fw, sw = re.search(r"i (.+?) foo and (.+?)(?:s|$)", string, flags=re.I).groups()
    print("first word:", fw)
    print("second word:", sw)

Where flags=re.I is needed for case insensitivity.

Answered By: Lucy Goodman
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.