62,046
社区成员
发帖
与我相关
我的任务
分享
public static string FormatBody(string body)
{
Regex reg = new Regex(@"(<a .+?</a>)|(<pre(>|\s).+?</pre>)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
Match mat = reg.Match(body);
List<string> str1 = new List<string>();
List<string> str2 = new List<string>();
int indx = 0;
while (mat.Success)
{
str1.Add(body.Substring(indx, mat.Index - indx));
str2.Add(mat.Value);
indx = mat.Index + mat.Length;
mat = reg.Match(body, indx);
}
str1.Add(body.Substring(indx));
str2.Add("");
StringBuilder sb = new StringBuilder();
int p = 50, cnt, len;
StringBuilder tmp;
Regex reg2;
Match mat2;
for (int i = 0; i < str1.Count; i++)
{
tmp = new StringBuilder(str1[i]);
if (Regex.Replace(tmp.ToString(), @"<.+?>", "").Length > 5)
{
cnt = tmp.Length / p;
len = 0;
foreach (string _tag in Tag.AllTags)//AllTags包含了站内所有关键字
{
//str = Regex.Replace(str, @"([^<]+?)(" + _tag + ")", "$1<a href='/tag/$2.htm'>$2</a>", RegexOptions.IgnoreCase);
reg2 = new Regex(@"((^|>)[^<]+?)(" + _tag + ")", RegexOptions.IgnoreCase);
mat2 = reg2.Match(tmp.ToString());
if (mat2.Success)
{
tmp.Remove(mat2.Index, mat2.Length);
tmp.Insert(mat2.Index, mat2.Groups[1].Value + "<a href='/tag/" + mat2.Groups[2].Value + ".htm'>" + mat2.Groups[2].Value + "</a>");
if (++len > cnt) break;
}
}
}
sb.Append(tmp.ToString());
sb.Append(str2[i]);
}
return sb.ToString();
}
mark