1、IsMatch
指示正则表达式在字符串中是否找到了匹配项
string pattern = "This";
string input = "This is one line and";
Regex regex = new Regex(pattern);
Console.WriteLine(regex.IsMatch(input));//从字符串的第一个字符开始寻找匹配
Console.WriteLine(regex.IsMatch(input,15));//从字符串的指定字符位置开始寻找匹配
输出:
True
False
2、Match
返回正则表达式的第一个匹配项
string pattern = "This";
string input = "This is one line and";
Regex regex = new Regex(pattern);
Console.WriteLine(regex.Match (input).Value ==""?"无": regex.Match(input).Value);
Console.WriteLine(regex.Match(input,15).Value ==""? "无": regex.Match(input, 15).Value);
Console.WriteLine(regex.Match(input, 0,3).Value ==""? "无": regex.Match(input, 0, 3).Value);
Console.WriteLine(regex.Match(input, 0, 4).Value ==""? "无": regex.Match(input, 0, 4).Value);
输出:
This
无
无
This
3、Matches
输出匹配的所有匹配项
string pattern = "This";
string input = "This is one line and This is second line";
Regex regex = new Regex(pattern);
MatchCollection matchCollection = regex.Matches(input);
foreach (Match item in matchCollection)
{
Console.WriteLine(item .Value );
}
Console.WriteLine();
matchCollection = regex.Matches(input,8);
foreach (Match item in matchCollection)
{
Console.WriteLine(item.Value);
}
输出:
This
This
This
4、Replace
找到匹配项,然后使用新的字符串去替换匹配项
string pattern = "This";
string input = "This is one line and This is second line, This is third line";
Regex regex = new Regex(pattern);
string replaceStr = "that";
string newString = regex.Replace(input, replaceStr);
Console.WriteLine(newString);
newString = regex.Replace(input, replaceStr, 2);//限制最大替换的个数
Console.WriteLine(newString);
newString = regex.Replace(input, replaceStr, 2, 8);//限制最大替换的个数,并且指定开始匹配的位置
Console.WriteLine(newString);
newString = regex.Replace(input, new MatchEvaluator (ReplaceString),2);//使用一个委托,这个委托对于每一个匹配的字符串进行处理,然后用这个新返回的字符串替换旧的匹配
Console.WriteLine(newString);
5、Split
string pattern = ",";
string input = "123,456,789,";
Regex regex = new Regex(pattern);
string[] strArray1 = regex.Split(input);
foreach (string str in strArray1)
{
Console.WriteLine(str);
}
Console.WriteLine();
string[] strArray2 = regex.Split(input,2);//指定最大分割的次数,达到次数以后就不分割了
foreach (string str in strArray2)
{
Console.WriteLine(str);
}
Console.WriteLine();
string[] strArray3 = regex.Split(input,2,5);//指定最大分割次数以及指定起始开始分割的位置
foreach (string str in strArray3)
{
Console.WriteLine(str);
}
输出:
123
456
789
123
456,789,
123,456
789,