-
C#正则表达式替换
string pattern = "(mr|dr) ([A-Z])[a-z]*";
string str = "mr Jhons$,dr Tom$";
Regex regex = new Regex(pattern);
var ouputStr = regex.Replace(str, "Mr X");
Console.WriteLine(ouputStr);
Console.WriteLine();
ouputStr = regex.Replace(str, "$1 X");//$group,使用group指定的组号
Console.WriteLine(ouputStr);
Console.WriteLine();
ouputStr = regex.Replace(str, "$2 X");//$group,使用group指定的组号
Console.WriteLine(ouputStr);
Console.WriteLine();
ouputStr = regex.Replace(str, "$+ X");//把找到的匹配使用最后一个组替换
Console.WriteLine(ouputStr);
Console.WriteLine();
pattern = "(?<groupName>mr|dr) ([A-Z])[a-z]*";
regex = new Regex(pattern);
ouputStr = regex.Replace(str, "${groupName} X");//把找到的所有匹配使用groupName替换
Console.WriteLine(ouputStr);
Console.WriteLine();
pattern = "mr [A-Z][a-z]*";
str = "mr Jhons!";
regex = new Regex(pattern);
ouputStr = regex.Replace(str, "$");//把找到的匹配使用$替换
Console.WriteLine(ouputStr);
Console.WriteLine();
pattern = "mr [A-Z][a-z]*";
str = "@!mr Jhons";
regex = new Regex(pattern);
ouputStr = regex.Replace(str, "$`");//把找到的匹配使用匹配前的文本去替换,在这里匹配前的文本是"@!"。
Console.WriteLine(ouputStr);
Console.WriteLine();
pattern = "mr [A-Z][a-z]*";
str = "%mr Jhons@!";
regex = new Regex(pattern);
ouputStr = regex.Replace(str, "$'");//把找到的匹配使用匹配后的文本去替换,在这里匹配后的文本是"@!"。
Console.WriteLine(ouputStr);
Console.WriteLine();
pattern = "mr [A-Z][a-z]*";
str = "%mr Jhons@!";
regex = new Regex(pattern);
ouputStr = regex.Replace(str, "$_");//把找到的匹配使用整个的字符串,也就是str的值来替换
Console.WriteLine(ouputStr);
string str = "mr Jhons$,dr Tom$";
Regex regex = new Regex(pattern);
var ouputStr = regex.Replace(str, "Mr X");
Console.WriteLine(ouputStr);
Console.WriteLine();
ouputStr = regex.Replace(str, "$1 X");//$group,使用group指定的组号
Console.WriteLine(ouputStr);
Console.WriteLine();
ouputStr = regex.Replace(str, "$2 X");//$group,使用group指定的组号
Console.WriteLine(ouputStr);
Console.WriteLine();
ouputStr = regex.Replace(str, "$+ X");//把找到的匹配使用最后一个组替换
Console.WriteLine(ouputStr);
Console.WriteLine();
pattern = "(?<groupName>mr|dr) ([A-Z])[a-z]*";
regex = new Regex(pattern);
ouputStr = regex.Replace(str, "${groupName} X");//把找到的所有匹配使用groupName替换
Console.WriteLine(ouputStr);
Console.WriteLine();
pattern = "mr [A-Z][a-z]*";
str = "mr Jhons!";
regex = new Regex(pattern);
ouputStr = regex.Replace(str, "$");//把找到的匹配使用$替换
Console.WriteLine(ouputStr);
Console.WriteLine();
pattern = "mr [A-Z][a-z]*";
str = "@!mr Jhons";
regex = new Regex(pattern);
ouputStr = regex.Replace(str, "$`");//把找到的匹配使用匹配前的文本去替换,在这里匹配前的文本是"@!"。
Console.WriteLine(ouputStr);
Console.WriteLine();
pattern = "mr [A-Z][a-z]*";
str = "%mr Jhons@!";
regex = new Regex(pattern);
ouputStr = regex.Replace(str, "$'");//把找到的匹配使用匹配后的文本去替换,在这里匹配后的文本是"@!"。
Console.WriteLine(ouputStr);
Console.WriteLine();
pattern = "mr [A-Z][a-z]*";
str = "%mr Jhons@!";
regex = new Regex(pattern);
ouputStr = regex.Replace(str, "$_");//把找到的匹配使用整个的字符串,也就是str的值来替换
Console.WriteLine(ouputStr);