如何从格式为“<name>_<fileNum>of<fileNumTotal>”或“<name>”的文件名中提取名称?

How to extract name from a file name in the form "<name>_<fileNum>of<fileNumTotal>" or "<name>"?

用户指定的文件名可以是“_of”或简单的“”形式。我需要以某种方式从完整文件名中提取“”部分。

基本上,我正在寻找以下示例中方法“ExtractName()”的解决方案:

string fileName = "example_File";  \ This var is specified by user
string extractedName = ExtractName(fileName);  // Must return "example_File"
fileName = "example_File2_1of5";
extractedName = ExtractName(fileName);  // Must return "example_File2"
fileName = "examp_File_3of15";
extractedName = ExtractName(fileName);  // Must return "examp_File"
fileName = "example_12of15";
extractedName = ExtractName(fileName);  // Must return "example"

编辑:这是我到目前为止尝试过的方法:

ExtractName(string fullName)
{
    return fullName.SubString(0, fullName.LastIndexOf('_'));
}

但这显然不适用于全名只是“”的情况。

谢谢

这会更容易使用 Regex 进行解析,因为您不知道这两个数字有多少位数。

var inputs = new[]
{
    "example_File",
    "example_File2_1of5",
    "examp_File_3of15",
    "example_12of15"
};

var pattern = new Regex(@"^(.+)(_\d+of\d+)$");
foreach (var input in inputs)
{
    var match = pattern.Match(input);
    if (!match.Success)
    {
        // file doesn't end with "#of#", so use the whole input
        Console.WriteLine(input);
    }
    else
    {
        // it does end with "#of#", so use the first capture group
        Console.WriteLine(match.Groups[1].Value);
    }
}

此代码returns:

example_File
example_File2
examp_File
example

Regex 模式包含三个部分:

  1. ^$ 是锚点,可确保您捕获整个字符串,而不仅仅是字符的子集。
  2. (.+) - 匹配一切,越贪心越好。
  3. (_\d+of\d+) - 匹配“_#of#”,其中“#”可以是任意数量的连续数字。