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

Python正则提取CSV文件名指定字段问题求助

解决文件名内容提取的正则问题

Hey there! Let's get that filename extraction sorted out for you. I see you're trying to pull the text between the last underscore and .csv from your filenames, and your current regex isn't working because it can't handle spaces or non-word characters. Let's fix this step by step.

问题分析

Your existing regex patterns use \w+, which only matches letters, numbers, and underscores—it doesn't include spaces (like in 'Base Media') or other characters you might have. Plus, we need to specifically target the content after the last underscore before .csv.

解决方案1:修正正则表达式

Use this regex pattern to capture exactly what you need:

import re

# 替换为你的all_data列表
filenames = [
    'Varying Concentration2_20190712-145158_Base Media.csv',
    'Varying Concentration2_20190712-145158_250 g per l.csv'
]

extracted = []
for fname in filenames:
    # 匹配最后一个下划线后到.csv前的所有内容
    match = re.search(r'(?<=_)[^_]+(?=\.csv$)', fname)
    if match:
        extracted.append(match.group())

print(extracted)
# 输出: ['Base Media', '250 g per l']

正则规则解释:

  • (?<=_): 正向断言,确保匹配位置紧跟在一个下划线之后
  • [^_]+: 匹配除下划线外的任意字符(包括空格),至少出现一次
  • (?=\.csv$): 正向断言,确保匹配位置紧跟在结尾的.csv之前

解决方案2:不用正则,用字符串分割(更直观)

如果觉得正则有点绕,用Python字符串方法反而更简单直接:

filenames = [
    'Varying Concentration2_20190712-145158_Base Media.csv',
    'Varying Concentration2_20190712-145158_250 g per l.csv'
]

extracted = []
for fname in filenames:
    # 从右侧开始分割一次下划线
    split_part = fname.rsplit('_', 1)
    if len(split_part) == 2:
        # 去掉第二部分的.csv后缀
        content = split_part[1].replace('.csv', '')
        extracted.append(content)

print(extracted)
# 输出: ['Base Media', '250 g per l']

为什么你之前的正则失效?

  • 第一个正则(?<=_)(\w+).csv$:\w+遇到'Base Media'里的空格就会停止匹配,只能捕获到'Base',而且没有正确排除.csv部分。
  • 第二个正则(?<=[0-9]+_)(\w+):它依赖最后一个下划线前是数字(比如你的日期),但依然无法处理空格,而且如果文件名最后一个下划线前不是数字的话,这个断言就完全不生效了。

内容的提问来源于stack exchange,提问作者Anh duong Le

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 09:09:10