用戶指定的檔案名可以采用“<name>_<fileNum>of<fileNumTotal>”或簡單的“<name>”形式。我需要以某種方式從完整檔案名中提取“<name>”部分。
基本上,我正在尋找以下示例中方法“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('_'));
}
但這顯然不適用于全名只是“<name>”的情況。
謝謝
uj5u.com熱心網友回復:
使用正則運算式會更容易決議,因為您不知道這兩個數字有多少位。
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);
}
}
此代碼回傳:
example_File
example_File2
examp_File
example
正則運算式模式包含三個部分:
^和$是錨點,以確保您捕獲整個字串,而不僅僅是字符的子集。(. )- 匹配一切,盡可能貪婪。(_\d of\d )- 匹配“_#of#”,其中“#”可以是任意數量的連續數字。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/376742.html
