一、如果字符串中只有一处匹配正则表达式,可用Result来获取匹配字。
例如:
string tmpUrl = "http://sports.163.com/nba/";
Regex r = new Regex(@"^http://(?<d>[^/]+)/", RegexOptions.Compiled);
realUrl = "http://" + r.Match(tmpUrl).Result("${d}") + href;
则:r.Match(tmpUrl).Result("${d}")的值为:sports.163.com
二、如果字符串中不只一处匹配正则表达式,可用MatchCollection来获取匹配字符集。
例如:获取字符串中所有的图片地址
string Content = ""; //要匹配的原字符串
string imageStr = "";
MatchCollection mc = Regex.Matches(Content, @"src=""(?<img>[^""]*?)""",RegexOptions.IgnoreCase | RegexOptions.Multiline);
foreach (Match m in mc)
{
imageStr = m.Groups["img"].Value.Trim();
if (imageStr.Length != 0)
{
//操作
}
}
或
string Content=""; //要匹配的原字符串
string imageStr = "";
strRegex = @"src=""(?<img>[^""]*?)""";
Regex re = new Regex(strRegex,RegexOptions.IgnoreCase | RegexOptions.Multiline);
MatchCollection matches = re.Matches(Content);
System.Collections.IEnumerator enu = matches.GetEnumerator();
while (enu.MoveNext() && enu.Current != null)
{
Match match = (Match)(enu.Current);
imageStr = match.Value;
if (imageStr.Length != 0)
{
//操作
}
}
不要忘记引用using System.Text.RegularExpressions命名空间哦!