列表中字符串中间的正则表达式(Python)

时间:2018-07-18 09:15:55

标签: python regex string list

我正在尝试使用正则表达式来匹配字符串中间的模式,其中字符串也在列表中。我可以找到一个问题或另一个问题的解决方案,但对如何将两个问题结合起来感到困惑。

首先,我使用this solution作为模板。我在“猫”和“牛”之后添加了文本,因此它们现在分别是“猫叫鲍勃”和“牛也叫鲍勃”。目的是从列表中的这两个字符串中提取单词“ named”,并将其作为列表中的项返回(例如['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)

但是,如果我使用r.search或r.findall,则会得到整个字符串,而不仅仅是中间部分。如果使用r.match,则不会得到任何结果。我在searching in the middle of a string上发现了一些Stack Overflow查询,但是它们似乎与在字符串中查找匹配项的解决方案不太匹配。我尝试了以下代码,但是没有用:

newlist = list(filter(r.match.group(1), mylist)) 

我将如何结合这两个任务并在列表内的字符串中间提取文本?

2 个答案:

答案 0 :(得分:1)

使用列表理解:

print([m.group() for m in map(r.search, mylist) if m])

这将输出:

['named', 'named']

答案 1 :(得分:1)

使用filter(r.search, mylist),您将只收到项中任何地方都存在正则表达式匹配项的所有项。当您使用filter(r.match, mylist)时,只会得到匹配项位于字符串开头的项目。

您可以使用

import re
mylist = ["dog", "cat named bob", "wildcat", "thundercat", "cow also named bob", "hooo"]
r = re.compile('named')
# You might gfo through the list, check if there is match 
# by running a re.search, and there is, extract it
newlist = [r.search(x).group() for x in mylist if r.search(x)]
print(newlist)
# Or, use map to get the matches first, and then 
# check if the object is not None and then retrieve the value
newlist = [x.group() for x in map(r.search, mylist) if x]
print(newlist)

请参见Python demo