Regular Expression for Finding Uses of CSS Classes

One thing that has always tripped me up when editing CSS for a large site, especially one that I am unfamiliar with, is making sure the edits I’m making in CSS are not going to affect anything I don’t want them to affect. Sites with hundreds or thousands of pages can have all sorts of nooks and crannies of legacy code and if I edit the CSS for say .button, what else will be affected?

One way I’ve recent found to solve this problem is with a regular expression. Searching for:

class="button"

.. will not find every instance where the .button class is used. For instance it will NOT find:

class="button next large"

Also, how do you find either usage across multiple files in multiple sub-folders?

1. Find across subfolders

First, lets start with finding across files in multiple folders and subfolders. I have recently started using EasyFind, this handy tool can search the contents of files within all sub folders of any folder currently selected in the Finder. In the above example, I would search simply for “button”, which would give me a list of all the files with that text somewhere within their contents. This could be quite a long list of files if “button” is used widely through your site. So.. step 2:

2. Find uses of CSS class name using regular expressions

In EasyFind, select all the results for the above search and right click to open them in your favorite text editor. TextWrangler works well for this case. All the files will open at once. Go to Search > Multi-File Search. In the search field type the following regular expression:

class=".*?button.*?"

This will search for the string class=" and then it will search for 0 or more instances *? of any character . then the string button followed again by 0 or more instances *? of any character . and finally finishing off with the closing double quote ".

This will find all of the below uses of the button class:

<div class="monkey zebra btn">Monkey Button</div>
<div class="btn monkey zebra"> Button</div>
<div class="zebra btn">Monkey "Button"</div>
<div class="btn">Monkey Button</div>
<div class="monkey btn zebra">Monkey Button</div>

And now you can safely know what elements will be effected by a change to CSS for the .button class and sleep easier tonight. Yea!