欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JS和C#實(shí)現(xiàn)的兩個(gè)正則替換功能示例分析

 更新時(shí)間:2017年06月01日 10:51:37   作者:穆穆  
這篇文章主要介紹了JS和C#實(shí)現(xiàn)的兩個(gè)正則替換功能,結(jié)合具體實(shí)例形式分析了js與C#進(jìn)行字符串正則替換的相關(guān)實(shí)現(xiàn)方法與注意事項(xiàng),需要的朋友可以參考下

本文實(shí)例講述了JS和C#實(shí)現(xiàn)的兩個(gè)正則替換功能。分享給大家供大家參考,具體如下:

應(yīng)用實(shí)例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");

應(yīng)用實(shí)例2:

待處理字符串:str="display=test name=mu display=temp"

要求:字符串變?yōu)閐isplay=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按查找到的字符串再根據(jù)分組進(jìn)行分組
  //第0組為整個(gè)符合的字符串,后面的組按括號(hào)順序排
  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);

最后還有一個(gè)關(guān)于js的正則的小總結(jié):

字符串match和正則對(duì)象exec的區(qū)別

1、 當(dāng)正則表達(dá)式?jīng)]有/g時(shí),兩者返回第一個(gè)符合的字符串或字符串組(如果正則中有分組的話)

2、 當(dāng)正則表達(dá)式有/g時(shí),match返回全部符合的字符串組且忽略分組,exec則返回第一個(gè)字符串或字符串組

PS:這里再為大家提供2款非常方便的正則表達(dá)式工具供大家參考使用:

JavaScript正則表達(dá)式在線測(cè)試工具:
http://tools.jb51.net/regex/javascript

正則表達(dá)式在線生成工具:
http://tools.jb51.net/regex/create_reg

希望本文所述對(duì)大家正則表達(dá)式學(xué)習(xí)有所幫助。

相關(guān)文章

最新評(píng)論