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

c#简单正则表达式~


①元旦:</strong>1月1日
②元旦:</strong>2007年12月30日



问题:能不能帮忙写一个正则表达式,可以匹配上面的2种情况 ,


结果:最后要获取的信息是(就是要获取几月几日):
1 1
12 30
c# 正则表达式

------解决方案--------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = @"①元旦:</strong>1月1日
②元旦:</strong>2007年12月30日";
            var result = Regex.Matches(s, @"元旦:\</strong\>(\d{4}年){0,1}(?<m>\d{1,2})月(?<d>\d{1,2})日");
            foreach (Match item in result)
                Console.WriteLine("{0} {1}", item.Groups["m"], item.Groups["d"]);
        }
    }
}



1 1
12 30
Press any key to continue . . .
------解决方案--------------------
 string s = @"①元旦:</strong>1月1日
②元旦:</strong>2007年12月30日";
MatchCollection matches=Regex.Matches(s,@"(?is)\w+:</strong>(?:\d{4}年)?(?<month>\d{1,2})月(?<date>\d{1,2})日");
foreach(Match match in matches)
    Console.WriteLine("{0}  {1}",match.Groups["month"].Value,match.Groups["date"].Value);


手写的,没调试过。
------解决方案--------------------

            string[] strs = new string[] { "元旦:</strong>1月1日", "元旦:</strong>2007年12月30日" };
            Regex regex = new Regex(@"(?<Month>\d+)月(?<Day>\d+)日");

            foreach (string str in strs)
            {
                Match match = regex.Match(str);
                Console.WriteLine(match.Groups["Month"].Value + " " + match.Groups["Day"].Value);
            }


------解决方案--------------------
(?<=</strong>(\d+年)?)(?<month>\d+)月(?<day>\d+)日