I have a string which contains a large amount of text and inside this text is a date in the format dd-MM-yyyy
. An example of this text is as follows
Composed by super, mtzshm to super, mtzshm on 31-Mar-2016 02:24 with Normal priority and Message Type General Message
I would like the date part of the text to be extracted using Regex and for it to be converted into a DateTime
For date time: \\d{2}-[Az]{3}-\\d{4}\\s\\d{2}:\\d{2}
For date: \\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 ':'
I'd like to know what the string will contains? Will it contain only DD-MM-YYYY or will it have other things?
If you pass only DD-MM-YYYY Already and want to turn it into a DateTime you can do a simple for loop without the use of regular expression
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);
This should work, just coded this directly on the site, tell me if that's not what you need, since there is not enough explanation.
Edit : Nvm you want to get the 31-Mar-2016 , which means it is not a DD-MM-YYYY format but a DD-MMM-YYYY format which gives this regular expression :
^(([0-9])|([0-2][0-9])|([3][0-1]))\-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\-\d{4}$
Following regex will capture just Date part from given string.
\b\d{1,2}\-[a-z]{3}\-\d{4}\b
Final code should look like
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);
}
If everything goes well, you'll see a nice date printed in your local format. In my case it'see
3/31/2016 12:00:00 AM
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.