簡體   English   中英

如何使用正則表達式從字符串中提取 dd-MMM-yyyy 中的日期

[英]How to extract date in dd-MMM-yyyy from string using regular expression

我有一個包含大量文本的字符串,在此文本中是dd-MM-yyyy格式的日期。 這段文字的一個例子如下

Composed by super, mtzshm to super, mtzshm on 31-Mar-2016 02:24 with Normal priority and Message Type General Message

我希望使用 Regex 提取文本的日期部分並將其轉換為 DateTime

對於日期時間: \\d{2}-[Az]{3}-\\d{4}\\s\\d{2}:\\d{2}

對於日期: \\d{2}-[Az]{3}-\\d{4}

\d{2}       Match a digit of length 2
-           Matches character '-'
[A-z]{3}    Matches a character in the Range 'A' to 'z' of length 3
[A-z]*      Matches a character in the Range 'A' to 'z' of length x
\s          Matches any white space character
:           Matches character ':'

我想知道字符串將包含什么? 它將只包含 DD-MM-YYYY 還是包含其他內容?

如果你只傳遞 DD-MM-YYYY 並且想要把它變成一個 DateTime 你可以做一個簡單的 for 循環而不使用正則表達式

string date = "DD-MM-YYYY";

string year = null;
string month = null;
string day = null;

for ( int i = 0; i < 10; ++i)
{
   if ( i < 2)
     day += date[i];
   if ( i > 2 && i < 5 )
     month += date[i];
   if ( i > 5 )
     year += date[i];
}

DateTime date = new DateTime();
date = date.AddYears(Convert.ToInt32(year)-1);
date = date.AddMonths(Convert.ToInt32(month)-1);
date = date.AddDays(Convert.ToInt32(day-1);

這應該可以工作,只是直接在網站上編碼,如果這不是您需要的,請告訴我,因為沒有足夠的解釋。

編輯:您想要獲得 31-Mar-2016 的 Nvm ,這意味着它不是 DD-MM-YYYY 格式,而是 DD-MMM-YYYY 格式,它給出了這個正則表達式:

^(([0-9])|([0-2][0-9])|([3][0-1]))\-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\-\d{4}$

以下正則表達式將僅捕獲給定字符串中的日期部分。

\b\d{1,2}\-[a-z]{3}\-\d{4}\b

最終代碼應該看起來像

var text = "Composed by super, mtzshm to super, mtzshm on 31-Mar-2016 02:24 with ";
text    += "Normal priority and Message Type General Message";

var rx = new Regex(@"\b\d{1,2}\-[a-z]{3}\-\d{4}\b", RegexOptions.IgnoreCase | RegexOptions.Multiline);

var match = rx.Match(text);
if (match.Success)
{
    var dateString = match.Value;
    var date = DateTime.Parse(dateString);

    Console.WriteLine(date);
}

如果一切順利,您將看到以本地格式打印的不錯的日期。 在我的情況下,它看到

3/31/2016 12:00:00 AM

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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