[英]C# substring in the middle
我有以下數據:
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個字符。
如何使用子串或其他方法解決這個問題?
您不需要找到.pdf
索引
path.Substring(path.Length - 14, 10)
我是用正則表達式做的。
^[\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
的子字符串,該字符串10_01_2013.pdf
為14個字符,但只占用前10
字符,剩下10_01_2013
。
但是,如果文件名采用不同的格式且日期可能出現在名稱中的任何位置,您可能需要考慮使用正則表達式來匹配##_##_####
並拉那個。
如果你想使用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個字符。
如果文件名的路徑發生變化(它可能會發生)並且不依賴於幻數(除了定義我們感興趣的子字符串長度的那個)之外,這些方法都將繼續工作,以找到正確的位置在字符串中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.