Python 如何使用正则表达式筛选列表?

Python 如何使用正则表达式筛选列表?,python,Python,我有一个字符串列表,其中的项目看起来像“{name,'test1'}”或“{name,test1'}”(注意test1周围的单引号/双引号) 如何筛选列表中的“测试”字符串,即我想要的: final_list = ['test1', 'test2', 'test3', 'test4'] 我相信有更好的方法来代替正则表达式,但既然你问: >>> import re >>> re.findall(r"""['"](test[^'"]*)['"]""", "".j

我有一个字符串列表,其中的项目看起来像
“{name,'test1'}”
“{name,test1'}”
(注意
test1
周围的单引号/双引号)

如何筛选列表中的“测试”字符串,即我想要的:

final_list = ['test1', 'test2', 'test3', 'test4']

我相信有更好的方法来代替正则表达式,但既然你问:

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

如果你确定每个列表中都有这样的例子,我会用这个:

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

当然,如果您不确定每个字符串中是否有可用的“testx”,这将不起作用。

这里有一种方法可以实现您想要的

注意:我已经稍微调整了你列表的内容,使之成为一个有效的列表(见其他评论)


您是如何创建此字符串列表的?很明显,您的数据结构早些时候出了问题。这些字符串肯定应该是
dict
s,而且一个单独的密钥对
dict
无论如何都是毫无意义的……试着在过滤器中进行正则表达式测试[1-9]如果这些字符串是您的真实数据,那么您的问题就完全无关紧要了。如果这些数据与您的真实数据不相似,则您不太可能收到对您有实际帮助的答案。可能的答案重复,并通过查找其中包含
“test”
。如果存在其他文本而不是testCorrect,则正则表达式不正确,将不匹配。我的理解是,只有尾随数字在变化。从我的评论来看,我并不是唯一一个误解你问题的人。如果test是任何单词,你将如何形成正则表达式呢?坦率地说,这是一个不同的问题,但是
r”““['”]([^']*)['”]['”
list1 = ["{name, 'test1'}", '{name, "test2"}', "{name, 'test3'}", '{name, "test4"}']
final_list = [re.search("[\'\"](.*?)[\'\"]", i).group(1) for i in list1]
print(final_list)
import re


def check_for_match(text):
    return re.findall("test[0-9]", text)[0]

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

res = [check_for_match(i) for i in list1]
print(res)
>>>['test1', 'test2', 'test3', 'test4']