CSS syntax Highlighting in c# with regex


I want to add CSS syntax highlighting to my rich text box in C#. How would I do that using regex e.g. highlighting the tag names/classes/id’s. I have this so far for HTM, but I would like to do for CSS too.

            string tags = @"<([/A-Za-z0-9]*)\b[^>]*>(.*?)";
            tagMatches = Regex.Matches(rtb.Text, tags, RegexOptions.Multiline);

            // getting attributes from the text 
            string attributes = @"[A-Za-z0-9-_]*=[A-Za-z0-9-_]*";
            attributeMatches = Regex.Matches(rtb.Text, attributes);

            // getting comments (inline or multiline)
            string comments = @"(\<![ \r\n\t]*(--([^\-]|[\r\n]|-[^\-])*--[ \r\n\t]*)\>)";
            commentMatches = Regex.Matches(rtb.Text, comments, RegexOptions.Multiline);

            // getting strings
            string strings = "(\".+?\"|\'.+?\')";
            stringMatches = Regex.Matches(rtb.Text, strings);


You can use this pattern to match classes/ids: ([\.#][_A-Za-z0-9\-]+)[^}]*{[^}]*}.


Answered By – Zroq

Answer Checked By – Mildred Charles (AngularFixing Admin)

Leave a Reply

Your email address will not be published.