使用正则表达式 regex.match 配合模式 _([^_]+)_ 可以准确提取文件名中两个下划线之间的部分。该做法通过捕获组获取中间文本,若不存在匹配项则返回空字符串,从而避免索引越界或逻辑错误。

如何验证输入格式并处理无匹配的情况
在调用 Regex.Match 后,必须检查 .Success 属性以确认是否找到目标片段。如果文件名格式不符合预期(如缺少下划线),程序应安全地返回默认值或空字符串,而不是抛出异常或返回错误数据。

using System;
using System.Text.RegularExpressions;
public class FileNameExtractor
{
public static string ExtractMiddlePart(string fileName)
{
// 定义正则表达式:匹配两个下划线之间的非下划线字符
string pattern = "_([^_]+)_";
Match match = Regex.Match(fileName, pattern);
if (match.Success)
{
return match.Groups[1].Value;
}
else
{
return string.Empty;
}
}
public static void Main()
{
string testFile = "report_v1_final.pdf";
string result = ExtractMiddlePart(testFile);
Console.WriteLine($"Extracted: '{result}'");
string badFile = "no_underscores.txt";
string badResult = ExtractMiddlePart(badFile);
Console.WriteLine($"Extracted from bad file: '{badResult}'");
}
}当文件名包含多个下划线时提取行为如何
正则表达式 _([^_]+)_ 默认匹配第一个符合条件的片段。如果文件名中有多个下划线对,Match 只返回第一个结果。若需提取所有片段,应使用 Regex.Matches 遍历所有匹配项,确保不会遗漏中间部分的任何内容。

using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
public class MultiFileNameExtractor
{
public static List<string> ExtractAllMiddleParts(string fileName)
{
string pattern = "_([^_]+)_";
MatchCollection matches = Regex.Matches(fileName, pattern);
List<string> results = new List<string>();
foreach (Match match in matches)
{
results.Add(match.Groups[1].Value);
}
return results;
}
public static void Main()
{
string complexFile = "a_b_c_d_e.txt";
List<string> parts = ExtractAllMiddleParts(complexFile);
Console.WriteLine("All middle parts:");
foreach (string part in parts)
{
Console.WriteLine(part);
}
}
}基于输入 "data_2023_export.csv" 的具体提取结果是什么
对于输入字符串 data_2023_export.csv,使用 Regex.Match 与模式 _([^_]+)_ 将成功匹配到 _2023_,并通过捕获组 1 提取出 2023。这是最直接的单片段提取场景,结果明确且稳定。


















