65.9K
CodeProject is changing. Read more.
Home

Manipulating CSS and HTML with RegEx

starIconstarIconstarIconemptyStarIconemptyStarIcon

3.00/5 (4 votes)

May 12, 2015

CPOL
viewsIcon

14741

This tip provides you with several RegEx find and replace patterns to search through and alter HTML and CSS.

Searching

This pattern will find all HTML elements with no children:

<([a-z]+)[ ]?[^<>]*[>][^<>]*</\1>

This pattern will find all HTML elements with self closing tags:

<[a-z]+[ ]?[^<>]*[ ]/>

Manipulating

HTML

You can use this pair of patterns to remove the "class" attribute of all HTML elements (or swap the word "class" for any other attribute's name):

Find

(<[^>]+)[ ]class="\w+"

Replace

$1

You can use this pair of patterns to remove all attributes of all HTML elements:

Find

(<\w+)[ ][^>/]+(?=/?>)

Replace

$1

CSS

This pair of patterns will shorten hexadecimal color values that qualify:

Find

#([0-9A-Fa-f])\1([0-9A-Fa-f])\2([0-9A-Fa-f])\3

Replace

#$1$2$3

This pair of patterns will remove the unit from values of zero:

Find

\b0(?:px|%|em|pt|in|pc)

Replace

0