实现一个自定义标记的解析...[Date:2009/2/1,Format:yyyy-MM-dd]  首先匹配出这个字符串,然后取 2009/2/1 和yyyy-MM-dd 把日期格式改为 2009-02-01  后在把整个标记的换成新的日期!这个表达要怎么写!

解决方案 »

  1.   

    [Date:2009/2/1,Format:yyyy-MM-dd] 就是把字符串中的这个标记替换成  "2009-02-01"
      

  2.   

    using System;
    using System.Text.RegularExpressions;class Program
    {
      static void Main()
      {
        string tag = "[Date:2009/2/1,Format:yyyy-MM-dd]";
        Match m = Regex.Match(tag, "(?i)date:([^,]+),format:([^\\]]+)");
        if (m.Success)
        {
          // 这就是你要的:
          tag = DateTime.Parse(m.Groups[1].Value).ToString(m.Groups[2].Value);
          Console.WriteLine(tag);  // 输出:2009-02-01
        }
      }
    }
      

  3.   

    using System;
    using System.Text.RegularExpressions;class Program
    {
      static void Main()
      {
        string s = "记住[Date:2009/2/1,Format:yyyy-MM-dd]这天,另外还有[Date:2010-07-09,Format:yy.M.d]。";
        string t = Regex.Replace(s, @"(?i)\[date:([^,]+),format:([^\]]+)\]", 
          delegate(Match m)
          {
            return DateTime.Parse(m.Groups[1].Value).ToString(m.Groups[2].Value);
          }
        );
        Console.WriteLine(t);  // 输出:记住2009-02-01这天,另外还有10.7.9。
      }
    }
      

  4.   

    "(?i)date:([^,]+),format:([^\\]]+)"); 这句我有点看不懂啊,楼上的能否再解释的详细点??
      

  5.   


    正准备问你多个标记怎么办,你就把把问题解决了,太强了!!结贴了!!   delegate(Match m)
          {
            return DateTime.Parse(m.Groups[1].Value).ToString(m.Groups[2].Value);
          }
    这段什么意思...没见过这种用法
      

  6.   

    如果你用的是 Visual Studio 2008,或者 C# 3.0 以上版本,可以使用 Linq 简化 delegate:
    using System;
    using System.Text.RegularExpressions;class Program
    {
      static void Main()
      {
        string s = "有[Date:2009/2/1,Format:yyyy-MM-dd],还有[Date:2010-07-09,Format:d'/'M'/'y]";
        string t = Regex.Replace(s, @"(?i)\[date:([^,]+),format:([^\]]+)\]",                         
          m => DateTime.Parse(m.Groups[1].Value).ToString(m.Groups[2].Value)
        );
        Console.WriteLine(t);  // 输出:有2009-02-01,还有9/7/10
      }
    }
      

  7.   

    我是用08的...Linq不太懂,还以为Linq只是用数据库方面的...!!不明白的是刚才我问的那段代码在在调用时执行了什么操作?
      

  8.   

    请参考:
    http://msdn.microsoft.com/zh-cn/library/system.text.regularexpressions.regex.replace.aspx我用的是:
    http://msdn.microsoft.com/zh-cn/library/ht1sxswy.aspx这里有程序例子:
    http://msdn.microsoft.com/zh-cn/library/cft8645c.aspx
      

  9.   

    另外,如果想得到 9/7/10 这样的效果,日期格式请用 d'/'M'/'y,也就是说 / 要用单引号引起来,否则输出的可能是 9-7-10,取决于你的电脑的“控制面板”中的“区域设置”中的“日期格式”的日期分隔符是什么。