Skip to content
Advertisement

Regular Expression: match word in a blank of a sentence

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.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement