跪求匹配日期的正则表达式!!

jacksoncan 2012-09-21 11:17:27
有一个表格里面有一个叫“时期”的string类型的字段,内容及格式如下:

时期

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

....

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



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;

}
}



...全文
135 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
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>

*/
bdmh 2012-09-21
  • 打赏
  • 举报
回复

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);
}
瑞卡哥哥 2012-09-21
  • 打赏
  • 举报
回复



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;

}
}


jacksoncan 2012-09-21
  • 打赏
  • 举报
回复
写错了,这是我随便举例的,真实的数据不会这样

[Quote=引用 1 楼 的回复:]

2012-06-31 ?

你比我多活一天?
[/Quote]
Nick黄 2012-09-21
  • 打赏
  • 举报
回复
2012-06-31 ?

你比我多活一天?
jacksoncan 2012-09-21
  • 打赏
  • 举报
回复
非常感谢各位高手的帮助

110,561

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧