C#正則匹配、分組和替換

來源:互聯網
上載者:User

用兩個執行個體來示範吧

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,有別的簡便寫法,見此文

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.