本文實例講述了JS和C#實現的兩個正則替換功能。分享給大家供大家參考,具體如下:
應用實例1:
待處理字符串:str="display=test name=mu display=temp"
要求:把display=后的值都改成localhost
JS處理方法:
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處理方法:
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則返回第一個字符串或字符串組
PS:這里再為大家提供2款非常方便的正則表達式工具供大家參考使用:
JavaScript正則表達式在線測試工具:
http://tools.jb51.net/regex/javascript
正則表達式在線生成工具:
http://tools.jb51.net/regex/create_reg
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com