2012年5月29日星期二

C#正则表达式辅助类

C#正则表达式辅助类

/// <summary>
/// 正则表达式 抓取需要的内容
/// </summary>
/// <param name="HtmlCode">HTML代码</param>
/// <param name="RegexString">正则表达式</param>
/// <param name="GroupKey">关键字</param>
/// <returns></returns>
public static string[] GetRegValue(string HtmlCode, string RegexString, string GroupKey)
{
MatchCollection m;
Regex r;
r = new Regex(RegexString, RegexOptions.Multiline | RegexOptions.Singleline);
m = r.Matches(HtmlCode);
string[] MatchValue = new string[m.Count];
for (int i = 0; i < m.Count; i++)
{
MatchValue[i] = m[i].Groups[GroupKey].Value;
}
return MatchValue;
}


/// <summary>
/// 正则表达式 抓取需要的内容(从右向左匹配)
/// </summary>
/// <param name="HtmlCode">HTML代码</param>
/// <param name="RegexString">正则表达式</param>
/// <param name="GroupKey">关键字</param>
/// <returns></returns>
public static string[] GetRegValueByRight(string HtmlCode, string RegexString, string GroupKey)
{
MatchCollection m;
Regex r;
r = new Regex(RegexString,RegexOptions.RightToLeft| RegexOptions.Multiline | RegexOptions.Singleline);
m = r.Matches(HtmlCode);
string[] MatchValue = new string[m.Count];
for (int i = 0; i < m.Count; i++)
{
MatchValue[i] = m[i].Groups[GroupKey].Value;
}
return MatchValue;
}


TAG: