在开发过程中,经常会使用到,使用正则表达式匹配Img标签,具体代码如下:
//正则表达式: <img(.*?)>
//在C#中使用代码实现方法如下
string html = ""; //此处为html代码
Regex regImg = new Regex(@"<img(.*?)>", RegexOptions.IgnoreCase);
MatchCollection matches = regImg.Matches(html);
if (matches != null && matches.Count > 0)
{
for (int j = 0; j < matches.Count; j++)
{
var img = matches[j]?.Value;
if (!string.IsNullOrEmpty(img))
{
var repimg = img;
repimg = Regex.Replace(repimg, "alt=\"(.*?)\"", $"alt=\"替换字符串\"", RegexOptions.Compiled);//过滤alt属性
repimg = Regex.Replace(repimg, "title=\"(.*?)\"", $"title=\"替换字符串\"", RegexOptions.Compiled);//过滤title属性
html = Regex.Replace(html, img, repimg, RegexOptions.Compiled);
}
}
}
使用正则表达式匹配html中 p标签下包含img标签的正则表达式,实现代码如下:
//正则表达式: <p\b[^<>]*>[^<>]*<img\b[^<>]*\/>[^<>]*<\/p>
//C#实现代码如下:
string html = ""; //此处为html代码
Regex regexPArray = new Regex(@"<p\b[^<>]*>[^<>]*<img\b[^<>]*\/>[^<>]*<\/p>", RegexOptions.IgnoreCase);
MatchCollection matchesValue = regexPArray.Matches(html);
if (matchesValue != null && matchesValue.Count > 0)
{
for (int i = 0; i < matchesValue.Count; i++)
{
var pValue = matchesValue[i]?.Value;
if (!string.IsNullOrEmpty(pValue))
{
Regex regImg = new Regex(@"<img(.*?)>", RegexOptions.IgnoreCase);
MatchCollection matches = regImg.Matches(pValue);
if (matches != null && matches.Count > 0)
{
for (int j = 0; j < matches.Count; j++)
{
var img = matches[j]?.Value;
if (!string.IsNullOrEmpty(img))
{
var repimg = img;
repimg = Regex.Replace(repimg, "alt=\"(.*?)\"", $"alt=\"替换字符串\"", RegexOptions.Compiled);//过滤alt属性
repimg = Regex.Replace(repimg, "title=\"(.*?)\"", $"title=\"替换字符串\"", RegexOptions.Compiled);//过滤title属性
html = Regex.Replace(html, pValue, repimg, RegexOptions.Compiled);
}
}
}
}
}
}
以上就是使用正则表达式匹配img标签或使用正则表达式匹配P标签中包含img的P标签使用方式。