用兩個執行個體來示範吧
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,有別的簡便寫法,見此文