簡體   English   中英

C#substring在中間

[英]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個字符。

如何使用子串或其他方法解決這個問題?

在這種情況下使用Substring

從此實例中檢索子字符串。 子字符串從指定的字符位置開始。

試試這樣;

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)

我是用正則表達式做的。

^[\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

但是,如果文件名采用不同的格式且日期可能出現在名稱中的任何位置,您可能需要考慮使用正則表達式來匹配##_##_####並拉那個。

嘗試這種方法:

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

請參閱此處: 僅從字符串中提取最右邊的n個字母

如果你想使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM