Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Manipulating CSS and HTML with RegEx

3.00/5 (4 votes)
11 May 2015CPOL 14.7K  
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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)