@"(S+)://(S+)"; //匹配URL的模式
foreach (Match match in mc)
{
Console.WriteLine(match.Value);
}
Console.ReadLine();
结果:
@"(?<protocol>S+)://(?<address>S+)"; //匹配URL的模式,并分组
MatchCollection mc = Regex.Matches(text, pattern); //满足pattern的匹配集合
Console.WriteLine("文本中包含的URL地址有:");
foreach (Match match in mc)
{
gc["protocol"].Value + ";Address:" + gc["address"].Value;
Console.WriteLine(outputText);
}
Console.Read();
示例2:使用带两个参数的构造函数,第二个参数指示忽略大小写,很常用
var source = "123abc345DEf";
Regex regex = new Regex("def",RegexOptions.IgnoreCase);
if (regex.IsMatch(source))
{
Console.WriteLine("字符串中包含有敏感词:def!");
}
Console.ReadLine();
使用Regex类进行替换
示例1:简单情况
var source = "123abc456ABC789";
// 静态方法
//var newSource=var newSource = Console.WriteLine("替换后的字符串:" + newSource);
Console.ReadLine();
结果:
原字符串:123abc456ABC789
替换后的字符串:123|456|789
示例2:将匹配到的选项替换为html代码,我们使用了MatchEvaluator委托
var source = "123abc456ABCD789";
Regex regex = new Regex("[A-Z]{3}", RegexOptions.IgnoreCase);
var newSource = Console.WriteLine("替换后的字符串:" + newSource);
Console.ReadLine();
private static string OutPutMatch(Match match)
{
return "<b>" +match.Value+ "</b>";
}
输出:
原字符串:123abc456ABCD789
替换后的字符串:123<b>abc</b>456<b>ABC</b>D789