通过实例来了解C#中的正则表达式

本篇将通过实例来了解C#中的正则表达式。

1. 通过正则表达式来查找重复的字符

private static void RegexMatch()
{
var input = "This my my test !";
var pattern = @"b(w+)s(1)";
Match match = Regex.Match(input, pattern);
while(match.Success)
{
Console.WriteLine("Duplication {0} found", match.Groups[1].Value);
match = match.NextMatch();
}
}

2. 通过正则表达式来查找并替换字符

private static void RegexReplace()
{
var input = "Total cost: 1023.43";
var pattern = @"bd+.d{2}b";
var replacement="$$$&";
Console.WriteLine(Regex.Replace(input,pattern,replacement));
}

3. 通过正则表达式来分隔字符

private static void RegexSplit() 
{
string input = "1. Egg 2. Bread 3. Milk 4. Coffee";
string pattern = @"bd{1,2}.s";
foreach(string item in Regex.Split(input,pattern))
{
if(!String.IsNullOrEmpty(item))
{
Console.WriteLine(item);
}
}
}

4. 通过正则表达式查找match的字符

private static void Matches()
{
MatchCollection matches;
Regex r = new Regex("abc");
matches = r.Matches("123abc4abcd");
foreach(Match match in matches)
{
Console.WriteLine("{0} found at position {1}", match.Value, match.Index);
}
}

5. 通过正则表达式Group数组来显示匹配字符

private static void Groups()
{
string input = "Born: July 28, 1989";
string pattern = @"b(w+)s(d{1,2}),s(d{4})b";

Match match = Regex.Match(input, pattern);
if(match.Success)
{
for(var i=0;i<match.Groups.Count;i++)
{
Console.WriteLine("Group {0}: {1}", i, match.Groups[i].Value);
}
}
}