You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用正则表达式过滤列表并提取目标字符串?

提取列表中引号内的"test"类字符串的方法

嘿,这个需求很明确,我平时处理这种固定格式的字符串提取,常用下面两种方法,都能轻松得到你想要的final_list:

方法一:正则表达式(通用且灵活)

正则可以精准匹配被单引号或双引号包裹的内容,不管引号类型,都能提取出来。直接用re.findall就能搞定:

import re

list1 = ["{name, 'test1'}", '{name, "test2"}', "{name, 'test3'}", '{name, "test4"}']
final_list = []
for item in list1:
    # 匹配单引号或双引号内的test开头字符串,捕获组提取引号里的部分
    match = re.findall(r"['\"](test\d+)['\"]", item)
    if match:
        final_list.extend(match)

print(final_list)  # 输出: ['test1', 'test2', 'test3', 'test4']

如果想更简洁,也可以用列表推导式一行搞定:

import re

list1 = ["{name, 'test1'}", '{name, "test2"}', "{name, 'test3'}", '{name, "test4"}']
final_list = [re.findall(r"['\"](test\d+)['\"]", item)[0] for item in list1]

注:如果你的字符串格式完全固定,不会出现多个匹配项的情况,用列表推导式就很高效;如果有不确定的情况,还是用循环加判断更稳妥。

方法二:字符串分割+去除引号(适合格式完全固定的场景)

因为你的每个列表项格式都是{name, 'xxx'}或{name, "xxx"},结构非常固定,所以可以直接通过字符串分割来处理:

list1 = ["{name, 'test1'}", '{name, "test2"}', "{name, 'test3'}", '{name, "test4"}']
final_list = []
for item in list1:
    # 先按逗号加空格分割,取第二部分
    quoted_part = item.split(', ')[1]
    # 去除前后的单引号或双引号
    test_str = quoted_part.strip('\'"')
    final_list.append(test_str)

print(final_list)  # 输出: ['test1', 'test2', 'test3', 'test4']

同样可以改成简洁的列表推导式:

list1 = ["{name, 'test1'}", '{name, "test2"}', "{name, 'test3'}", '{name, "test4"}']
final_list = [item.split(', ')[1].strip('\'"') for item in list1]

这种方法不需要导入额外模块,代码更轻量,前提是你能保证所有列表项的格式都和示例一致。

内容的提问来源于stack exchange,提问作者Azhar Saleem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:29:42