输出匹配的部分:
public static void Main(string[] args)
{
string text = "I've found this amazing URL at http://www.sohu.com ,and then find ftp://ftp.sohu.com is better.";
string pattern = @"\b(\S+)://(\S+)\b"; //匹配URL的模式
MatchCollection mc = Regex.Matches(text, pattern); //满足pattern的匹配集合
Console.WriteLine("文本中包含的URL地址有:");
foreach (Match match in mc)
{
Console.WriteLine(match.ToString());
}
Console.Read();
}
/*
* 运行后输出如下:
* 文本中包含的URL地址有:
* http://www.sohu.com
* ftp://ftp.sohu.com
*/
提取字符串中的一部分,使用Group方法:
public static void Main(string[] args)
{
string text = "I've found this amazing URL at http://www.sohu.com ,and then find ftp://ftp.sohu.com is better.";
string pattern = @"\b(?<protocol>\S+)://(?<address>\S+)\b"; //匹配URL的模式,并分组
MatchCollection mc = Regex.Matches(text, pattern); //满足pattern的匹配集合
Console.WriteLine("文本中包含的URL地址有:");
foreach (Match match in mc)
{
GroupCollection gc = match.Groups;
string outputText = "URL:" + match.Value + "; Protocol:" + gc["protocol"].Value + "; Address:" + gc["address"].Value;
Console.WriteLine(outputText);
}
Console.Read();
}
/**
* 运行后输出如下:
* 文本中包含的URL地址有:
* URL:http://www.sohu.com;Protocol:http;Address:www.sohu.com
* URL:ftp://ftp.sohu.com;Protocol:ftp;Address:ftp.sohu.com
*/
正则表达式基础:http://www.cnblogs.com/dragon/archive/2006/05/08/394078.html
http://www.cnblogs.com/dragon/archive/2006/05/09/394923.html