本文實例講述了JS和C#實現的兩個正則替換功能。分享給大家供大家參考,具體如下:
應用實例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");
應用實例2:
待處理字符串:str="display=test name=mu display=temp"
要求:字符串變為display=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按查找到的字符串再根據分組進行分組 //第0組為整個符合的字符串,后面的組按括號順序排 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);
最后還有一個關于js的正則的小總結:
字符串match
和正則對象exec
的區別
1、 當正則表達式沒有/g時,兩者返回第一個符合的字符串或字符串組(如果正則中有分組的話)
2、 當正則表達式有/g時,match返回全部符合的字符串組且忽略分組,exec則返回第一個字符串或字符串組
希望本文所述對大家正則表達式學習有所幫助。
新聞熱點
疑難解答