c#通用正则解析代码,抓取数据无需再写正则
比如一段html:
<td>t1</td>
<td>t2</td>
<td>t3</td>
我们想取出<td>与</td>之间的值,使用如下捕获组正则即可达到要求:
调用:GetHtmls(“<td>”, “</td>”, html)
/// <summary>
/// 返回匹配多个的集合值
/// </summary>
/// <param name="start">开始html tag</param>
/// <param name="end">结束html tag</param>
/// <param name="html">html</param>
/// <returns></returns>
public static List<string> GetHtmls(string start, string end, string html)
{
IList list = new List<string>();
try
{
string pattern = string.Format("{0}(?<g>(.|[\r\n])+?){1}", start, end);//匹配URL的模式,并分组
MatchCollection mc = Regex.Matches(html, pattern);//满足pattern的匹配集合
if (mc.Count != 0)
{
foreach (Match match in mc)
{
GroupCollection gc = match.Groups;
list.Add(gc["g"].Value);
}
}
}
catch {}
return list;
}
对于单组,可以:
public static string GetHtml(string start, string end, string html)
{
string ret = string.Empty;
try
{
string pattern = string.Format("{0}(?<g>(.|[\r\n])+?)?{1}", start, end);//匹配URL的模式,并分组
ret= Regex.Match(html, pattern).Groups["g"].Value;
}
catch { }
return ret;
}