日期:2014-05-17  浏览次数:20796 次

跪求匹配日期的正则表达式!!
有一个表格里面有一个叫“时期”的string类型的字段,内容及格式如下:

时期

2012-05-31 到 2012-06-01
2012-06-31 到 2012-08-01
-- 到 --
2012-06-31 到 --
-- 到 2012-08-01

....

现在需要将字段里面的日期部分给“匹配”出来,并且分成“开始日期”和“截止日期”两个部分,分别赋值给两个相应的string变量,应该怎么做呢?请高手们帮忙,谢谢

C# code


string period = this.dataGridView1.Rows[this.dataGridView1.Rows.Count - 2].Cells["时期"].Value 
    
//这里以下的不会写呀            
string pattern = @""; 

                Regex regex = new Regex(pattern);
                MatchCollection mc = regex.Matches(period);
                if (mc.Count > 0)
                {
                    foreach (Match m in mc)
                    {
                        开始日期 = m.Groups[0].Value;
                        截止日期 = m.Groups[1].Value;

                    }
                }






------解决方案--------------------

C# code


string period = this.dataGridView1.Rows[this.dataGridView1.Rows.Count - 2].Cells["时期"].Value 
    
//这里以下的不会写呀            
string pattern = @"((--)|(\d{4}-\d{2}-\d{2}))\s到\s((\d{4}-\d{2}-\d{2})|(--))"; 

                Regex regex = new Regex(pattern);
                MatchCollection mc = regex.Matches(period);
                if (mc.Count > 0)
                {
                    foreach (Match m in mc)
                    {
                        开始日期 = m.Groups[1].Value;
                        截止日期 = m.Groups[4].Value;

                    }
                }

------解决方案--------------------
C# code

            StreamReader reader = new StreamReader("c:\\1.txt",Encoding.Default);
            string source = reader.ReadToEnd();
            Regex reg = new Regex(@"(?is)(\d{4}-\d{2}-\d{2}) 到 (\d{4}-\d{2}-\d{2})");
            MatchCollection mc = reg.Matches(source);
            foreach (Match m in mc)
            {
                MessageBox.Show("开始:" + m.Groups[1].Value + "  结束:" + m.Groups[2].Value);
            }

------解决方案--------------------
C# code
string pattern = @"(\d{4}-\d{1,2}-\d{1,2}|--)\s*?到\s*?(\d{4}-\d{1,2}-\d{1,2}|--)";
                string tempStr = File.ReadAllText(@"C:\Documents and Settings\Administrator\桌面\Test.txt", Encoding.GetEncoding("GB2312"));//读取txt

                var result = Regex.Matches(tempStr, pattern).Cast<Match>().Select(a => new { 
                    开始日期=a.Groups[1].Value,
                    结束日期=a.Groups[2].Value
                });
                /*
                 * +        [0]    { 开始日期 = "2012-05-31", 结束日期 = "2012-06-01" }    <Anonymous Type>
+        [1]    { 开始日期 = "2012-06-31", 结束日期 = "2012-08-01" }    <Anonymous Type>
+        [2]    { 开始日期 = "--", 结束日期 = "--" }    <Anonymous Type>
+        [3]    { 开始日期 = "2012-06-31", 结束日期 = "--" }    <Anonymous Type>
+        [4]    { 开始日期 = "--", 结束日期 = "2012-08-01" }    <Anonymous Type>

                 */