我有以下数据:
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个字符。
如何使用子串或其他方法解决这个问题?
答案 0 :(得分:5)
在这种情况下使用 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
。
答案 1 :(得分:4)
您无需查找.pdf
path.Substring(path.Length - 14, 10)
答案 2 :(得分:3)
我是用正则表达式做的。
^[\w:\\]+cloture_(\d+)_([\d_]+).pdf$
会匹配第二组中的日期。
答案 3 :(得分:2)
如果文件名始终采用该格式,您可以执行以下粗略操作:
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
。
但是,如果文件名采用不同的格式且日期可能出现在名称中的任何位置,您可能需要考虑像正则表达式这样的内容才能匹配##_##_####
并将其拉出来
答案 4 :(得分:0)
尝试这种方法:
string dateString = textString.Substring(textString.Length-14, 10);
答案 5 :(得分:0)
如果你想使用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
}
答案 6 :(得分:0)
我会考虑使用LastIndexOf
“。pdf”,然后倒数。或者使用Path.GetFileNameWithoutExtension
方法获取名称,然后使用最后10个字符。
如果文件名的路径发生变化(可能会发生变化)并且不依赖于幻数(除了定义我们感兴趣的子字符串长度的数字)之外,这些方法都会继续工作字符串中的正确位置。