Home > Web Front-end > JS Tutorial > body text

Share two examples of regular replacement functions implemented in JS and C#

巴扎黑
Release: 2017-06-16 10:27:35
Original
1265 people have browsed it

This article mainly introduces the two regular replacement functions implemented by JS and C#, and analyzes the relevant implementation methods and precautions for string regular replacement in JS and C# based on specific examples. Friends in need can refer to the following

The examples in this article describe 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 object exec

1. When the regular expression does not have /g, the two return the first matching character String or string group (if there are groups in the regular expression)

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

The above is the detailed content of Share two examples of regular replacement functions implemented in JS and C#. 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