[英]C# Regex based date parsing and extraction
我的問題很簡單:我需要從以下輸入中提取第一個日期:
# 12/29/2014 00:00 - 1/5/2015 00:00
現在,我已經使用通過互聯網找到的正則表達式列表實現了這個方法,我認為正確解析日期時間值:
string datePattern = @"^(((((((0?[13578])|(1[02]))[\.\-/]?((0?[1-9])|([12]\d)|(3[01])))|(((0?[469])|(11))[\.\-/]?((0?[1-9])|([12]\d)|(30)))|((0?2)[\.\-/]?((0?[1-9])|(1\d)|(2[0-8]))))[\.\-/]?(((19)|(20))?([\d][\d]))))|((0?2)[\.\-/]?(29)[\.\-/]?(((19)|(20))?(([02468][048])|([13579][26])))))$";
private string extractDate(string line) {
return System.Text.RegularExpressions.Regex.Match(line, datePattern, RegexOptions.CultureInvariant).Value.Trim();
}
我認為Match.Value
是一個屬性,它引用了Regex類的解析器匹配的第一個匹配字符串。 但它返回一個空字符串。
你能幫我解決這個簡單的問題嗎?
提前謝謝了。
您只需在拆分字符串后使用DateTime.ParseExact
方法:
var stringToParse = "# 12/29/2014 00:00 - 1/5/2015 00:00";
var splitValues = stringToParse.Split('-');
var firstSplitted = splitValues[0].Split(' ', StringSplitOptions.RemoveEmptyEntries);
var neededDateTime = DateTime.ParseExact(firstSplitted[1], "MM/dd/yyyy", CultureInfo.InvariantCulture);
非常感謝大家。 基於對VMAtm的善意建議,我已經為這個愚蠢的問題做了這個可怕的解決方案,這花了我很多時間。 我將日期分為年,月和日,而不是返回格式為“MM / dd / yyyy”的新DateTime(而不是dd / MM / yyyy,如前所述)。
如果您對此解決方案感到震驚,請原諒我,即使本月只有一位數,它似乎也能正常工作。
private string extractDate(string line)
{
var splitValues = line.Split('-');
var firstSplitted = splitValues[0].Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var dateSplitted = firstSplitted[1].Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
return new DateTime(Convert.ToInt32(dateSplitted[2]), Convert.ToInt32(dateSplitted[1]), Convert.ToInt32(dateSplitted[0])).ToString("MM/dd/yyyy");
}
任何其他更優雅的解決方案都是非常接受的。 再次感謝大家。
目前尚不清楚:字符串以“#”或數字開頭。 在任何情況下,一般模式是:
private static string extractDate(string line)
{
string datePattern = @"(?<=# |^)\d{1,2}/\d{1,2}/\d{1,4} \d{1,2}:\d{1,2}";
return System.Text.RegularExpressions.Regex.Match(line, datePattern, RegexOptions.CultureInvariant).Value.Trim();
}
控制台測試的主要方法:
static void Main(string[] args)
{
var testLines = new List<string> {
@"# 12/29/2014 00:00 - 1/5/2015 00:00",
@"12/29/2014 00:00 - 1/5/2015 00:00",
@"2/9/14 00:00 - 1/5/2015 00:00",
@"# 2/9/14 00:9 - 1/5/2015 00:00"
};
testLines.ForEach(t => Console.WriteLine(String.Format("{0} -> {1}", t, extractDate(t))));
}
您可以使用它來獲取兩個日期:
string input = "12/29/2014 00:00 - 1/5/2015 00:00";
Regex regex = new Regex(@"(?<month>(1[0-2]|0\d|\d))/(?<day>(3[0-1]|[0-2]\d|\d))/(?<year>[1-2]\d{3})\s(?<hour>(2[0-3]|[0-1]\d)):(?<min>[0-5]\d)");
MatchCollection match = regex.Matches(input);
foreach (Match m in match)
{
string year = m.Groups["year"].Value;
string month = m.Groups["month"].Value;
string day = m.Groups["day"].Value;
string hour = m.Groups["hour"].Value;
string min = m.Groups["min"].Value;
Trace.WriteLine(m.Groups["year"].Value);
Trace.WriteLine(m.Groups["month"].Value);
Trace.WriteLine(m.Groups["day"].Value);
Trace.WriteLine(m.Groups["hour"].Value);
Trace.WriteLine(m.Groups["min"].Value);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.