c#用正则表达式获取新闻资讯内容中img标签和src属性 |
您所在的位置:网站首页 › img标签src属性 › c#用正则表达式获取新闻资讯内容中img标签和src属性 |
有时我们列表需要显示文章的缩略图,但是每篇文章我们又没有单独的存这样的一张图,这个时候就需要我们程序自动的去获取文章内容中的img标签,找到新闻资讯内容中插入的第一张图片。在c#中我们可以用正则表达式很轻松我搞定。 要用到的正则表达式:
正则表达式获取文章内容第一张图的src属性C#代码: public string GetFirstImageFormNewsContentByNewsID(long newsID) { string content=DAL.GetNewsContentPageOneByNewsID(newsID); var match=Regex.Match(content,""); if (match != null && match.Groups.Count > 1) { return match.Groups[1].Value; } else return ""; }
正则表达式获取文章内容全部图的rcn属性C#代码: public List GetImagesFormNewsContentByNewsID(long newsID) { string content = DAL.GetNewsContentPageOneByNewsID(newsID); var matches = Regex.Matches(content, "", RegexOptions.IgnoreCase); var list=new List(); foreach (Match match in matches) { if (match != null && match.Groups.Count > 1) { list.Add(match.Groups[1].Value); } } return list; }本例主要用到了正则的分组和懒惰模式。上面是没有考虑到src为单引号和img标签换行的情况,如果有把这些所有情况都考虑上就要用下面的正则表达式了:
|
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |