本文实例报告了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则返回第一个字符串或字符串组
以上就是C#+JS完成的两个正则替代功用示例剖析的细致内容,更多请关注ki4网别的相干文章!