C#正则匹配、分组和替换

用两个实例来演示吧

1,有个项目引用WebService的,因为同时发在了几台服务器上,为了方便切换,我就要能动态去更改它的IP(只是IP不同,不是WebService不同),所以我只要替换其中的服务器地址部分就可以了

2,演示从查询字符串里面提取想要的资料,以便把这些资料恢复到网页上,类似asp.net的viewstate功能

        private string testrex(Match m)
        {
            //组0,就是所有匹配,然后依次为各个括号内的
            return m.Groups[1] + "/88.88.88.88:1000" + m.Groups[3];
        }

        protected void regexTest()
        {
            //测试正则替换
            string s = "http://221.221.221.221:8180/ws/services/n_ophospitaldoctorservice?wsdl";

            //替换IP地址加端口号为88.88.88.88:1000
            Regex rx = new Regex(@"(https?:/)(/[^/]+)(/.*)");

            MatchEvaluator me = new MatchEvaluator(testrex);
            //s = rx.Replace(s, me);//方法1,委托的方式
            s = rx.Replace(s, "$1/88.88.88.88:1000$3"); //方法2,替换字符串的方式
            //不把88.88.88.88:1000定义成一个变量,是为了方便演示为什么我把http://拆成了(http:/)和(/221.232.137...),
            //比如上面的,假如我拆成(https?://)的话,就要写成rx.Replace(s,"$188.88.88.88:100$3"),显然,$1变成$88了,
            //这是任何用$来表示组号的情况下需要注意的
            //相反,上面的MatchEvaluator的用法就不存在这个问题了,因为用的是group,而不是$
            Response.Write(s);
            Response.Write("<br/>");

            //获取查询字符串里面的日期
            string depSelectedSql = " 1=1  and reserve_date>=to_date('2010-10-10','yyyy-mm-dd') and reserve_date<=to_date('2010-11-10','yyyy-mm-dd')";

            Regex r = new Regex(@"reserve_date.=to_date.'(\d\d\d\d-\d\d-\d\d)", RegexOptions.IgnoreCase);
            MatchCollection mc = r.Matches(depSelectedSql);
            if (mc.Count < 2)
            {
                Response.Write("invalid query string!");
                return;
            }
            string sdate = mc[0].Groups[1].Value;
            string edate = mc[1].Groups[1].Value;

            Response.Write(sdate + "<br/>" + edate);
        }

结果:

http://88.88.88.88:1000/ws/services/n_ophospitaldoctorservice?wsdl
2010-10-10
2010-11-10

关于MatchEvaluator,有别的简便写法,见此文

原文地址:https://www.cnblogs.com/walkerwang/p/1947698.html