如何使用正则表达式过滤列表?

时间:2018-01-26 11:23:54

标签: python

我有一个字符串列表,其中的项目看起来像List<C<?, ?>>"{name, 'test1'}"(请注意'{name, "test1"}'周围的单/双引号)。

test1

如何过滤&#34;测试&#34;的列表?字符串,这是我想要的:

list1 = ["{name, 'test1'}", '{name, "test2"}', "{name, 'test3'}", '{name, "test4"}']

3 个答案:

答案 0 :(得分:1)

我确信有更好的方法来代替正则表达式,但是因为你问:

>>> import re
>>> re.findall(r"""['"](test[^'"]*)['"]""", "".join(list1))
['test1', 'test2', 'test3', 'test4']

答案 1 :(得分:1)

如果您确定每个列表中都有这样的实例,我会使用它:

list1 = ["{name, 'test1'}", '{name, "test2"}', "{name, 'test3'}", '{name, "test4"}']
final_list = [re.search("[\'\"](.*?)[\'\"]", i).group(1) for i in list1]
print(final_list)

当然,如果您不确定每个字符串中是否存在'testx',则无效。

答案 2 :(得分:0)

这是达到你想要的一种方式。

注意:我稍微调整了您的内容列表,使其成为有效列表(参见其他评论)。

SELECT *
FROM   public.geom_table
WHERE  column_latlng 
    @ -- contained by
    POLYGON((-6.6796875 39.111328125, -29.1796875 20.478515625, -32.6953125 -10.810546875, 12.65625 -24.873046875, 32.34375 1.142578125, 21.26953125 31.201171875, 17.75390625 38.759765625, -6.6796875 39.111328125))
相关问题