本文實(shí)例講述了JS和C#實(shí)現(xiàn)的兩個(gè)正則替換功能。分享給大家供大家參考,具體如下:
應(yīng)用實(shí)例1:
待處理字符串:str="display=test name=mu display=temp"
要求:把display=后的值都改成localhost
JS處理方法:
str.replace(/display=/w*/g,"display=localhost");
C#處理方法:
Regex reg=new Regex(@"display=/w*");str=reg.Replace(str,"display=localhost");
應(yīng)用實(shí)例2:
待處理字符串:str="display=test name=mu display=temp"
要求:字符串變?yōu)閐isplay=localhosttest name=mu display=localhosttemp
JS處理方法:
var reg = /(display=)(/w*)/g;var result;while ((result= reg.exec(str))!=null) { str= str.replace(result[0], result[1] + "localhost" + result[2]);}
C#處理方法:
/// <summary>/// 定義處理方法/// </summary>/// <param name="match">符合的字符串</param>/// <returns></returns>private string Evaluator(Match match){ //(display=)(/w*) Groups按查找到的字符串再根據(jù)分組進(jìn)行分組 //第0組為整個(gè)符合的字符串,后面的組按括號(hào)順序排 string str =match.Groups[1].Value+"localhost"+ match.Groups[2].Value; return str;}Regex regex = new Regex(@"(display=)(/w*)");string result = regex.Replace(str, Evaluator);
最后還有一個(gè)關(guān)于js的正則的小總結(jié):
字符串match
和正則對(duì)象exec
的區(qū)別
1、 當(dāng)正則表達(dá)式?jīng)]有/g時(shí),兩者返回第一個(gè)符合的字符串或字符串組(如果正則中有分組的話)
2、 當(dāng)正則表達(dá)式有/g時(shí),match返回全部符合的字符串組且忽略分組,exec則返回第一個(gè)字符串或字符串組
PS:這里再為大家提供2款非常方便的正則表達(dá)式工具供大家參考使用:
JavaScript正則表達(dá)式在線測(cè)試工具:
http://tools.VeVB.COm/regex/javascript
正則表達(dá)式在線生成工具:
http://tools.VeVB.COm/regex/create_reg
希望本文所述對(duì)大家正則表達(dá)式學(xué)習(xí)有所幫助。
新聞熱點(diǎn)
疑難解答