C# 拆分文件名-子字符串?
我有以下文件名: 上海合作组织秘书处1.pdf 上海合作组织登记处10.pdf SCO_Insu 100.pdf SCO_Insu 1000.pdf 我正在使用FileInfo读取文件名,并希望将其拆分,以便只获得1、10、100或1000个数字。我如何实现这一点C# 拆分文件名-子字符串?,c#,.net,C#,.net,我有以下文件名: 上海合作组织秘书处1.pdf 上海合作组织登记处10.pdf SCO_Insu 100.pdf SCO_Insu 1000.pdf 我正在使用FileInfo读取文件名,并希望将其拆分,以便只获得1、10、100或1000个数字。我如何实现这一点 filename = filename.Substring(filename.lastIndexOf("_")+1); filename = filename.Substring(0, filename.indexOf("."));
filename = filename.Substring(filename.lastIndexOf("_")+1);
filename = filename.Substring(0, filename.indexOf("."));
或者
filename = Regex.Replace(filename, "_(\d+).pdf$", "$1");
或者
filename = Regex.Replace(filename, "_(\d+).pdf$", "$1");
当然,最好使用一些边界检查来避免索引异常
当然,最好使用一些边界检查来避免索引异常。使用正则表达式:
string number = Regex.Match("SCO_InsBooking_1000.pdf", @"\d+").Value;
假设文件名中没有其他数字。使用正则表达式:
string number = Regex.Match("SCO_InsBooking_1000.pdf", @"\d+").Value;
假设文件名中没有其他数字。可以使用正则表达式执行此操作:
Regex.Match(filename, @".*_(\d+).pdf").Groups[1].Value
可以使用正则表达式执行此操作:
Regex.Match(filename, @".*_(\d+).pdf").Groups[1].Value
您可以使用string.replace
using System.Collections.Generic;
namespace strings1
{
class Program
{
static void Main(string[] args)
{
List<string> names = new List<string> {
"SCO_InsBooking_1.pdf",
"SCO_InsBooking_10.pdf",
"SCO_InsBooking_100.pdf",
"SCO_InsBooking_1000.pdf" };
List<string> numbers = new List<string>();
foreach (string item in names)
{
numbers.Add(item.Replace("SCO_InsBooking_", string.Empty).Replace(".pdf",string.Empty));
}
}
}
}
您可以使用string.replace
using System.Collections.Generic;
namespace strings1
{
class Program
{
static void Main(string[] args)
{
List<string> names = new List<string> {
"SCO_InsBooking_1.pdf",
"SCO_InsBooking_10.pdf",
"SCO_InsBooking_100.pdf",
"SCO_InsBooking_1000.pdf" };
List<string> numbers = new List<string>();
foreach (string item in names)
{
numbers.Add(item.Replace("SCO_InsBooking_", string.Empty).Replace(".pdf",string.Empty));
}
}
}
}