我已经看到了一些线程,并尝试了其中提供的解决方案,但我似乎无法解决这个问题。我有一个正则表达式,以mm/dd/yyyy , mm/dd/yyyy
格式检查两个日期。中间可以有任意数量的空格。我的表达式适用于http://regexr.com/,但是当我在VS中运行代码时,正则表达式检查始终为false。任何帮助将不胜感激!
var reg = new Regex(@"\d{1,2}\/\d{1,2}\/\d{1,4}[ ]{0,}\,[ ]{0,}\d{1,2}\/\d{1,2}\/\d{1,4}");
Console.WriteLine("Please enter two dates in dd/mm/yyyy format seperated by a comma");
string datesIn = Console.ReadLine();
while (reg.IsMatch(datesIn) != true);
{
Console.WriteLine("Sorry, please make sure to enter your dates in dd/mm/yyyy format seperated by a comma.");
datesIn.Replace(datesIn, Console.ReadLine());
}
String[] dates = datesIn.Split(',');
foreach (var date in dates)
Console.WriteLine(date.Trim());
Console.ReadLine();
答案 0 :(得分:2)
我强烈建议您使用TryParse
using System;
using System.Globalization;
public class Program
{
public static void Main()
{
var input = "12/10/2012, 12/15/2015";
String[] dates = input.Split(',');
if(dates.Length != 2){
Console.WriteLine("I said 2 dates");
} else {
foreach (var date in dates)
{
DateTime parsedDate;
if(DateTime.TryParse(date, new CultureInfo("es"), DateTimeStyles.None, out parsedDate))
{
Console.WriteLine("{0} Perfect!", parsedDate);
}
else
{
Console.WriteLine("{0} Not right sir!", date);
}
}
}
Console.ReadLine();
}
}