正则表达式过滤掉CSS样式

class Program
    {
        static void Main(string[] args)
        {

            var text = "<span style=\"margin-left: 2em;color: #008000;font-size:14px;\">博问,解决您的IT难题!</span>" +
                       "<div style=\"margin-left: 2em;color: #008000;font-size:14px;\">博问,解决您的IT难题!</div>" +
                       "<span style=\"margin-top: 2em;color: #008000;font-size:14px;\">博问,解决您的IT难题!</span>" +
                       "<div style=\"margin-right: 2em;color: #008000;\">博问,解决您的IT难题!</div>" +
                       "<span style=\"margin-left: 2em;color: #008000;font-size:14px;\">博问,解决您的IT难题!</span>";
            var styleReg = new Regex(@"\sstyle=""(?<style>([^"";]+;?)+)""", RegexOptions.IgnoreCase);
            MatchCollection matches = styleReg.Matches(text);
            var matchesCount = matches.Count;
            if (matchesCount > 0)
            {
                foreach (Match match in matches)
                {
                    var oldStyle = match.Groups["style"].Value;
                    var styles = oldStyle.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
                        .ToList()
                        .Select(s => new
                                         {
                                             k = s.Split(':')[0],
                                             v = s.Split(':')[1]
                                         }).Where(s => s.k == "color" || s.k == "font-size" || s.k == "font-weight").ToList();
                    var result = string.Empty;
                    foreach (var s in styles)
                    {
                        result += s.k + ":" + s.v + ";";
                    }
                    //var result = styles.k + ":" + styles.v + ";" + styles1.k + ":" + styles1.v + ";";
                    text = text.Replace(oldStyle, result);
                }
            }
            //<span style="color: #008000;">博问,解决您的IT难题!</span>
            Console.WriteLine(text);
        }

 

posted @ 2017-06-01 13:55  字里行间  阅读(1532)  评论(0编辑  收藏  举报