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

如何使用Python从字符串列表中提取各组对应的公共前缀子串

实现方法

你可以通过正则匹配提取符合规则的前缀,该方案不需要硬编码前缀长度,适配不同结构的前缀规则。

核心逻辑

观察目标前缀的共有特征:

  • 前缀结尾的前一段要么是1-2位数字,要么是2位小写字母,且末尾固定为下划线
  • 用非贪婪匹配从字符串开头匹配到符合上述特征的位置即可

代码实现

import re

# 原始数据
data = [
    'blah_12_1_bbc_services_cbbc',
    'blah_12_1_high-profile_and_a',
    'blah_12_1_iplayer,_known',
    'blah_12_1_sport,_as_co-branded',
    'er_ds_such_it',
    'er_ds_websites_bbc_video',
    'er_ds_bbc',
    'er_ds_service._sport,',
    'th_ss_13_a',
    "th_ss_13_iplayer,_large_bbc's",
    'th_ss_13_the_a_co-branded',
    "th_ss_13_the_bbc's_bbc's"
]

# 定义正则匹配规则
prefix_pattern = re.compile(r'^.*?(?:_\d{1,2}|_[a-z]{2})_')

# 提取前缀
result = [prefix_pattern.match(item).group() for item in data]

print(result)

输出结果

运行上述代码后得到的结果和需求完全一致:

['blah_12_1_',
 'blah_12_1_',
 'blah_12_1_',
 'blah_12_1_',
 'er_ds_',
 'er_ds_',
 'er_ds_',
 'er_ds_',
 'th_ss_13_',
 'th_ss_13_',
 'th_ss_13_',
 'th_ss_13_']

兼容处理

如果存在部分字符串匹配不到的情况,可以加判断做兼容:

result = []
for item in data:
    match = prefix_pattern.match(item)
    result.append(match.group() if match else item)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 08:45:03