用正则表达式获取所有img标签

时间:2022-10-17 19:39:41
 public static string ReplaceOrAddImageTitle(string content, string title)
{
Regex reg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);
MatchCollection mc = reg.Matches(content); string oldString = "", newString = "";
if (mc.Count > )
oldString = mc[].Value; if (oldString.IndexOf("alt=") == -)
newString = oldString.Replace("<img ", "<img alt='" + title + "' ");
content = content.Replace(oldString, newString);
return content;
}
 public static string ReplaceOrAddImageTitle1(string content, string title)
{
int startIndex = content.IndexOf("<img ");
int endIndex = content.IndexOf(">", startIndex);
string oldString = content.Substring(startIndex, endIndex - startIndex + );
string newString = ""; if (oldString.IndexOf("alt=") == -)
newString = oldString.Replace("<img ", "<img alt='" + title + "' ");
else
{
startIndex = oldString.IndexOf("alt");
int index1 = oldString.IndexOf("'");
int index2 = oldString.IndexOf("\"");
if (index1 < index2)
endIndex = oldString.IndexOf("'", index1 + );
else
endIndex = oldString.IndexOf("\"", index2 + ); string altStr = oldString.Substring(startIndex, endIndex - startIndex + );
newString = oldString.Replace(altStr, " ").Replace("<img ", "<img alt='" + title + "' ");
}
content = content.Replace(oldString, newString);
return content;
}