Home > Software design >  Regular Expression: match word in a blank of a sentence
Regular Expression: match word in a blank of a sentence

Time:11-07

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.

CodePudding user response:

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.

  • Related