最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
JS和C#实现的两个正则替换功能示例分析
时间:2022-06-29 01:30:12 编辑:袖梨 来源:一聚教程网
本文实例讲述了JS和C#实现的两个正则替换功能。分享给大家供大家参考,具体如下:
应用实例1:
待处理字符串:str="display=test name=mu display=temp"
要求:把display=后的值都改成localhost
JS处理方法:
| 代码如下 | 复制代码 |
| str.replace(/display=w*/g,"display=localhost"); | |
C#处理方法:
| 代码如下 | 复制代码 |
|
Regex reg=newRegex(@"display=w*"); str=reg.Replace(str,"display=localhost"); | |
应用实例2:
待处理字符串:str="display=test name=mu display=temp"
要求:字符串变为display=localhosttest name=mu display=localhosttemp
JS处理方法:
| 代码如下 | 复制代码 |
|
varreg = /(display=)(w*)/g; varresult; while((result= reg.exec(str))!=null) { str= str.replace(result[0], result[1] +"localhost"+ result[2]); } | |
C#处理方法:
| 代码如下 | 复制代码 |
|
/// /// 定义处理方法 /// ///符合的字符串 /// privatestringEvaluator(Match match) { //(display=)(w*) Groups按查找到的字符串再根据分组进行分组 //第0组为整个符合的字符串,后面的组按括号顺序排 stringstr =match.Groups[1].Value+"localhost"+ match.Groups[2].Value; returnstr; } Regex regex =newRegex(@"(display=)(w*)"); stringresult = regex.Replace(str, Evaluator); | |
最后还有一个关于js的正则的小总结:
字符串match和正则对象exec的区别
1、 当正则表达式没有/g时,两者返回第一个符合的字符串或字符串组(如果正则中有分组的话)
2、 当正则表达式有/g时,match返回全部符合的字符串组且忽略分组,exec则返回第一个字符串或字符串组
PS:这里再为大家提供2款非常方便的正则表达式工具供大家参考使用:
JavaScript正则表达式在线测试工具:
http://tools.*j**b51.net/regex/javascript
正则表达式在线生成工具:
http://tools.j**b*51.net/regex/create_reg
希望本文所述对大家正则表达式学习有所帮助。
相关文章
- 星球重启轮胎资源位置分享 轮胎在哪 12-06
- tevi魔人多斯怎么打 魔人多斯打法攻略 12-06
- 星球重启菱锰矿在哪 菱锰矿采集地点 12-06
- 星球重启求生指南室友共建攻略 12-06
- 星球重启原晶怎么用 原晶使用方法 12-06
- 星球重启源码升级方法 源码怎么升级 12-06