您的位置:首页 > Web前端 > JavaScript

关于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则返回第一个字符串或字符串组



  

  

  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: