关于JS和C#的正则替换两个小例子
2012-08-24 00:32
295 查看
应用实例:
待处理字符串:str=”display=testname=mudisplay=temp”
要求:把display=后的值都改成localhost
JS处理方法:
str.replace(/display=\w*/g,”display=localhost”);
C#处理方法:
Regexreg=newRegex(@”display=\w*”); str=reg.Replace(str,”display=localhost”);
应用实例:
待处理字符串:str=”display=testname=mudisplay=temp”
要求:字符串变为display=localhosttestname=mudisplay=localhosttemp
JS处理方法:
varreg=/(display=)(\w*)/g; varresult; while((result=reg.exec(str))!=null){ str=str.replace(result[0],result[1]+"localhost"+result[2]); }
C#处理方法:
///<summary> ///定义处理方法 ///</summary> ///<paramname="match">符合的字符串</param> ///<returns></returns> privatestringEvaluator(Matchmatch) { //(display=)(\w*)Groups按查找到的字符串再根据分组进行分组 //第0组为整个符合的字符串,后面的组按括号顺序排 stringstr=match.Groups[1].Value+"localhost"+match.Groups[2].Value; returnstr; } Regexregex=newRegex(@"(display=)(\w*)"); stringresult=regex.Replace(str,Evaluator);
最后还有一个关于js的正则的小总结:
字符串match和正则对象exec的区别
1、当正则表达式没有/g时,两者返回第一个符合的字符串或字符串组(如果正则中有分组的话)
2、当正则表达式有/g时,match返回全部符合的字符串组且忽略分组,exec则返回第一个字符串或字符串组
相关文章推荐
- JS和C#实现的两个正则替换功能示例分析
- c#关于Delegate最简单的例子:两个窗体间的消息传递
- C#/JS 利用正则表达式 替换/删除 img 里面的 width height
- 关于 js中 数组删除 和替换的例子(splice 和 slice)(w3cschool)
- C# 关于字符串中 符合正则表达式的指定字符的替换的方法
- c#关于Delegate最简单的例子:两个窗体间的消息传递
- 地址栏批量替换C#正则表达式例子
- C# 用正则表达式替换字符串中所有特殊字符
- JS正则截取两个字符串之间及字符串前后内容的方法
- C# 两个API函数.[关于插入光标]
- JS使用正则截取两个字符串之间的字符串实现方法详解
- js正则表达式中关于零宽断言的奇异现象
- C# 正则过滤html,js,css代码
- JS使用replace()方法和正则表达式进行字符串的搜索与替换实例
- [转载]js正则表达式/replace替换变量方法
- 转:收集两个关于xml和xsl的例子。
- 关于更改jdk源码替换应用的例子
- JS利用正则配合replace替换指定字符
- js正则表达式例子
- C#中关于委托练习的一个例子