I'm trying to use a regular expression to match a pattern in the middle of a string where the strings are also in a list. I can find the solution to one problem or the other, but confused on how to combine the two.
First off, I'm using this solution as a template. I added text after "cat" and "cow", so they are now "cat named bob" and "cow also named bob". The goal is to extract the word "named" from those two strings in the list, and return them as items in a list (e.g. ['named', 'named']).
mylist = ["dog", "cat named bob", "wildcat", "thundercat", "cow also named bob", "hooo"]
r = re.compile('named')
newlist = list(filter(r.search, mylist))
print(newlist)
If I use r.search or r.findall, however, I get the entire string, rather than just the middle part. If I use r.match, I get no results. I found a few Stack Overflow queries on searching in the middle of a string, but they don't seem to go well with the solution for finding matches in a string. I tried the following code, but it didn't work:
newlist = list(filter(r.match.group(1), mylist))
How would I combine these two tasks and extract text in the middle of a string inside of a list?