中间的c#子字符串
本文关键字:字符串 中间 | 更新日期: 2023-09-27 17:53:08
我有以下数据:
D:'toto'food'Cloture_49000ert1_10_01_2013.pdf
D:'toto'food'Cloture_856589_12_01_2013.pdf
D:'toto'food'Cloture_66rr5254_10_12_2012.pdf
如何提取日期部分?例如:
D:'toto'food'Cloture_49000ert1_10_01_2013.pdf --> 10_01_2013
D:'toto'food'Cloture_856589_12_01_2013.pdf --> 12_01_2013
D:'toto'food'Cloture_66rr5254_10_12_2012.pdf --> 10_12_2012
我的想法是使用LastIndexOf(".pdf")
,然后向后数10个字符。
如何使用子字符串或其他方法解决这个问题?
在这种情况下使用 Substring
从此实例检索子字符串。子字符串从a开始指定字符位置。
试试;
string s = "D:''toto''food''Cloture_490001_10_01_2013.pdf";
string newstring = s.Substring(s.Length - 14, 10);
Console.WriteLine(newstring);
这里是 DEMO
您不需要查找.pdf
索引
path.Substring(path.Length - 14, 10)
我会用Regex来做。
^['w:'']+cloture_('d+)_(['d_]+).pdf$
将匹配第二组中的日期
如果文件名总是这种格式,您可以像这样做一些粗糙的操作:
string filename = @"D:'toto'food'Cloture_490001_10_01_2013.pdf";
string date = filename.Substring(filename.Length - 14, 10);
这将从10_01_2013.pdf
获得一个子字符串,该子字符串长14个字符,但只取10
的第一个字符,留下10_01_2013
。
但是,如果文件名是不同的格式,并且日期可能出现在名称中的任何地方,您可能需要考虑像正则表达式这样的东西,以便能够对##_##_####
进行匹配并将其拉出来。
试试这个方法:
string dateString = textString.Substring(textString.Length-14, 10);
从字符串
如果你想使用LastIndexOf,那么
string str = @"D:'toto'food'Cloture_490001_10_01_2013.pdf";
string temp = str.Substring(str.LastIndexOf(".pdf") - 10, 10);
你可以解析成
DateTime dt;
if(DateTime.TryParseExact(temp, "MM_dd_yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
//valid
}
else
{
//invalid
}
我同意你的想法,使用LastIndexOf
".pdf",然后向后计数。或者使用Path.GetFileNameWithoutExtension
方法只获取名称,然后获取最后10个字符。
如果文件名的路径发生了变化(很可能会发生),这些方法都将继续工作,并且不依赖于幻数(除了定义我们感兴趣的子字符串长度的那个)来找到字符串中的正确位置。