源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

JS和C#实现的两个正则替换功能示例分析

  • 时间:2022-12-01 04:18 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:JS和C#实现的两个正则替换功能示例分析
本文实例讲述了JS和C#实现的两个正则替换功能。分享给大家供大家参考,具体如下: [b]应用实例1:[/b] 待处理字符串: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");

[b]应用实例2:[/b] 待处理字符串: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);

[b]最后还有一个关于js的正则的小总结:[/b] 字符串[code]match[/code]和正则对象[code]exec[/code]的区别 1、 当正则表达式没有/g时,两者返回第一个符合的字符串或字符串组(如果正则中有分组的话) 2、 当正则表达式有/g时,match返回全部符合的字符串组且忽略分组,exec则返回第一个字符串或字符串组 [b]PS:这里再为大家提供2款非常方便的正则表达式工具供大家参考使用:[/b] [b]JavaScript正则表达式在线测试工具: [/b][url=http://tools.jb51.net/regex/javascript]http://tools.jb51.net/regex/javascript[/url] [b]正则表达式在线生成工具: [/b][url=http://tools.jb51.net/regex/create_reg]http://tools.jb51.net/regex/create_reg[/url] 希望本文所述对大家正则表达式学习有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部