C# 中间C字串

C# 中间C字串,c#,string,substring,C#,String,Substring,我有以下数据: 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_1

我有以下数据:

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个字符

如何使用子字符串或其他方法解决此问题?

尝试以下方法:

string dateString = textString.Substring(textString.Length-14, 10);

请参见此处:

您不需要查找
.pdf

path.Substring(path.Length - 14, 10)

如果文件名始终为该格式,则可以执行以下操作:

string filename = @"D:\toto\food\Cloture_490001_10_01_2013.pdf";

string date = filename.Substring(filename.Length - 14, 10);
这将从
10\u 01\u 2013.pdf
中获取一个子字符串,该子字符串长度为14个字符,但只获取第一个
10
字符,剩下的是
10\u 01\u 2013

如果文件名是不同的格式,日期可能出现在名称中的任何地方,您可能需要考虑一些类似正则表达式的东西,以便能够匹配< <代码> >第二类> >代码>并将其拉出。 从此实例检索子字符串。子字符串从a开始 指定的字符位置

像这样尝试

string s = "D:\\toto\\food\\Cloture_490001_10_01_2013.pdf";
string newstring = s.Substring(s.Length - 14, 10);
Console.WriteLine(newstring);

这是一个。

我会用正则表达式来做这件事

^[\w:\\]+cloture_(\d+)_([\d_]+).pdf$

将与第二组中的日期匹配。

如果要使用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”,然后倒数。或者使用该方法仅获取名称,然后获取最后10个字符


如果文件名的路径发生变化(可能会发生变化),这些方法将继续工作,并且不依赖幻数(定义我们感兴趣的子字符串长度的幻数除外)在字符串中找到正确的位置

我假设所有文件名都以
dateString.pdf
结尾,顺便提一下,
D:\toto\food\Cloture\u 49000ert1\u 10\u 01\u 2013.pdf
不是一个有效的字符串。如果你仔细想想,它仍然依赖于神奇的数字/定位。
子字符串
解决方案并不依赖于相同长度的文件名。@rudiviser-好的,只需要子字符串长度的幻数。是的,但它与
子字符串
相同,只是我们假设扩展名也是3个字符:)