正则非贪婪匹配

原文链接:http://www.cnblogs.com/linlin/archive/2011/03/12/1982403.html
string str = "注册商: XIAMEN ENAME NETWORK TECHNOLOGY CORPORATION LIMITED DBA ENAME CORP,"
            + "域名服务器: whois.ename.com,"
            + "相关网站: http://www.ename.com,"
            + "DNS 服务器: NS1.ENAME.NET,"
            + "DNS 服务器: NS2.ENAME.NET,"
            + "DNS 服务器: NS3.ENAME.NET,"
            + "DNS 服务器: NS4.ENAME.NET,"
            + "DNS 服务器: NS5.ENAME.NET,"
            + "DNS 服务器: NS6.ENAME.NET,"
            + "状态: clientDeleteProhibited,"
            + "状态: clientTransferProhibited,"
            + "更新时间: 10-mar-2011,"
            + "创建时间: 07-mar-2007,"
            + "过期时间: 07-mar-2016";
        Regex reg = new Regex(@"(?is)(?<=注册商:)([^,]*?)|(?<=更新时间:)([^,]*?)|(?<=创建时间:)([^,]*?)|(?<=过期时间:)([^,]*?)");
        MatchCollection match = reg.Matches(str);
        foreach (Match m in match)
        {
            if (m.Groups[1].Success)
                Response.Write(m.Groups[1].Value + "<br/>");
            if (m.Groups[2].Success)
                Response.Write(Convert.ToDateTime(m.Groups[2].Value).ToString("yyyy-MM-dd") + "<br/>");
            if (m.Groups[3].Success)
                Response.Write(Convert.ToDateTime(m.Groups[3].Value).ToString("yyyy-MM-dd") + "<br/>");
            if (m.Groups[4].Success)
                Response.Write(Convert.ToDateTime(m.Groups[4].Value).ToString("yyyy-MM-dd") + "<br/>");
        }

今天在写个上面的正则,结果一直匹配不出东西来,原来是非贪婪模式的错。这里不说非贪婪模式的效率

一般我们在匹配,

例如在匹配这个的时候

string str="<a href=\"http://www.cnblogs.com\">cnblogs</a>";
Regex reg = new Regex(@"(?i)<a[^>]*?href=(['""\s]?)([^'""\s]+)\1[^>]*?>")

[^>]*?非贪婪模式右边是href也就是匹配到href才停止

而(?<=注册商:)([^,]*?)这个正则([^,]*?)右边内容是空,也就是没有其他任何字符,所以就匹配空出来

记录下来以便日后又忘记了

转载于:https://www.cnblogs.com/linlin/archive/2011/03/12/1982403.html

上一篇:(2)centos图形界面


下一篇:eclipse中配置maven