使用re模块

时间:2017-12-13 06:57:07

标签: python python-3.x

我有一份如下所示的清单:

['\'STATE\\\': \\\'("DEVELOPMENT COMPLETE", "DEVELOPMENT IN PROGRESS", "WIP QA")\\\'}, \']']

现在我想使用re模块从提到的列表中过滤下面的部分。

("DEVELOPMENT COMPLETE", "DEVELOPMENT IN PROGRESS", "WIP QA")

任何人都可以帮我使用re模块吗?

1 个答案:

答案 0 :(得分:2)

使用:

>>> l = ['\'STATE\\\': \\\'("DEVELOPMENT COMPLETE", "DEVELOPMENT IN PROGRESS", "WIP QA")\\\'}, \']'] 
>>> re.search(r'(\([^\)]*\))' , l[0]).group(1)
'("DEVELOPMENT COMPLETE", "DEVELOPMENT IN PROGRESS", "WIP QA")'

如果您希望结果为tuple,则可以始终使用ast

>>> import ast
>>> ast.literal_eval(re.search(r'(\([^\)]*\))', l[0]).group(1))
('DEVELOPMENT COMPLETE', 'DEVELOPMENT IN PROGRESS', 'WIP QA')

以防万一,如果您的列表包含多个元素,那么您可能需要迭代它然后使用上面的re