MatchCollection 类表示成功的非重叠匹配的只读的集合,MatchCollection 的实例是由 Regex.Matches 属性返回的,下面的实例说明了通过在输入字符串中找到所有与Regex中指定的匹配并填充 MatchCollection。
1、MatchCollection mc;
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
Regex r = new Regex("match");
mc = r.Matches("matchcollectionregexmatchs");
for (int i = 0; i < mc.Count; i++)
{
Response.Write( mc[i].Value + " POS:" + mc[i].Index.ToString() + "<br>");
}
该实例运行的结果是:
match POS:0
match POS:20
2、public static string GetUrl(string text)
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
public static string GetUrl(string text)
{
string pattern = @"(http|ftp|https):\/\/[\w]+(.[\w]+)([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])";
MatchCollection matchs;
matchs = Regex.Matches(text,pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
foreach (Match m in matchs)
{
text = text.Replace(m.ToString(), "<a target=\"_new\" href=\"" + m.ToString() + "\">" + m.ToString() + "</a>");
}
return text;
}
Mark.