Home > Backend Development > C#.Net Tutorial > Analysis of two examples of regular replacement functions implemented in C#+JS

Analysis of two examples of regular replacement functions implemented in C#+JS

黄舟
Release: 2017-06-04 09:39:01
Original
1424 people have browsed it

This article mainly introduces the two regular replacement functions implemented by JS and C#, and analyzes the string between js and C# based on specific examples. Related implementation methods and Notes of regular replacement, friends in need can refer to the following

The examples in this article describe the two regular replacement functions implemented by JS and C#. Share it with everyone for your reference, the details are as follows:

Application example 1:

String to be processed: str="display=test name =mu display=temp"

Requirement: Change the values ​​after display= to localhost

JS processing method:

str.replace(/display=\w*/g,"display=localhost");
Copy after login

C#Processing method:

Regex reg=new Regex(@"display=\w*");
str=reg.Replace(str,"display=localhost");
Copy after login

Application Example 2:

String to be processed: str="display=test name=mu display=temp"

Requirement: The string becomes display= localhosttest name=mu display=localhosttemp

JS processing method:

var reg = /(display=)(\w*)/g;
var result;
while ((result= reg.exec(str))!=null) {
  str= str.replace(result[0], result[1] + "localhost" + result[2]);
}
Copy after login

C#Processing method:

/// <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);
Copy after login

Finally, there is a small summary about js regularity:

The difference between string match and regular objectexec

1. When the regular expression does not have /g, both return the first matching string or string group (if there is grouping in the regular expression)

2. When the regular expression contains /g, match returns all matching string groups and ignores grouping, and exec returns the first string or string group

The above is the detailed content of Analysis of two examples of regular replacement functions implemented in C#+JS. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
c# js
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template