正则表达式搜索列表,但 return 个相同大小的列表

regular expressions search list, but return list of same size

类似于这个问题:Regular Expressions: Search in list

但我想要 return 一个与搜索列表大小相同的列表,其中 None'' 没有匹配项:

import re

mylist = ["dog", "cat", "wildcat", "thundercat", "cow", "hooo"]
r = re.compile(".*cat")
list(filter(r.match, mylist)) 

# looking for  ["", "cat", "wildcat", "thundercat", "", ""]

我尝试删除 filter 但 return 是整个列表

也试过

[r.match(x) for x in mylist]

但是这个 returns:

[None,
 <regex.Match object; span=(0, 3), match='cat'>,
 <regex.Match object; span=(0, 7), match='wildcat'>,
 <regex.Match object; span=(0, 10), match='thundercat'>,
 None,
 None]

而且我不知道如何提取字符串

.group(0)None

抛出错误

两种方法都有效,优先考虑faster/more有效的方法,因为列表会很长

这是一种方法:

[m.group(0) if m else "" for m in map(r.match, mylist)]

生产:

['', 'cat', 'wildcat', 'thundercat', '', '']

非正则表达式的解决方案也应该没问题。

如果希望字符串以cat结尾,可以使用str.endswith:

>>> [x if x.endswith('cat') else '' for x in mylist]
['', 'cat', 'wildcat', 'thundercat', '', '']

如果cat可以出现在字符串的任意位置,可以使用in运算符:

>>> [x if 'cat' in x else '' for x in mylist]
['', 'cat', 'wildcat', 'thundercat', '', '']

您可以在正则表达式中使用交替来获得不匹配的空匹配:

import re

mylist = ["dog", "cat", "wildcat", "thundercat", "cow", "hooo"]
rx = re.compile(r'.*cat|^')

print( [rx.findall(i)[0] for i in mylist] )

正则表达式 .*cat|^ 匹配具有 cat 的字符串,或者当 cat 不匹配时只匹配行开头以确保空匹配。

RegEx Demo

输出:

['', 'cat', 'wildcat', 'thundercat', '', '']

只需将 and x 添加到您几乎成功的尝试中:

[r.match(x) and x for x in mylist]

结果:

[None, 'cat', 'wildcat', 'thundercat', None, None]

[m(x) and x for x in mylist]

m = r.match 之后。