Search code examples
pythonpython-re

Python : Get word from string where substring is present in string


I am new to Python and still learning basic concepts of it. I was wondering if there is any easy way to get all the words from a sentence where my search string matches the substrings of any words.

sentence = "Hi this is just an example.com sentence"
search = ".com"

Output :

example.com

I tried to use re module but got stuck at point where I need to fetch the whole word. This is what I have tried which returns the whole sentence as output:

re.findall(f".*{search}*", sentence)

I wanted to know if I am using the right approach or if there is any other way to solve this.

Additional Question :

Using reference of John's answer, [w for w in sentence.split() if '.com' in w] I am able to get the expected output. As an additional requirement, if

sentence = "Hi this is just an Example.COM sentence" 

I still want it to match with .com and return Example.COM


Solution

  • Please consider what pattern have you created

    sentence = "Hi this is just an example.com sentence"
    search = ".com"
    print(f".*{search}*")
    

    gives output

    .*.com*
    

    that does match any character (.) repeated zero or more times (*) followed by any character (.) followed by single character c followed by single character o followed by character m repeated zero or more times.

    I would use re following way in this case

    import re
    sentence = "Hi this is just an example.com or example.COM sentence"
    search = ".com"
    found = re.findall(f"\\w*{re.escape(search)}\\w*",sentence,re.IGNORECASE)
    print(found)
    

    gives output

    ['example.com', 'example.COM']
    

    Explanation: I use re.escape so . in search is treated as literal dot, not any character, I am looking for search prefixed and suffixed by zero-or-more (*) word characters (\w) and do that in case-insensitive way using re.IGNORECASE flag.