On countless occasions you've undoubtedly used Spotlight to search for a file on your Mac, or your word processor's Find and Replace feature to locate or change text. But sometimes a simple search doesn't cut it, even with the addition of simple wildcards like ? for any single character or * for multiple characters. For example, what if I want to find every instance of a caption in a book I'm working on — something like "Figure 42: Blah blah blah" and make just the figure number (and the trailing colon) bold — but not touch any references to those figures (like "see Figure 42") in the body text?
In cases like these, which I encounter on a daily basis, I use a regular expression (or "regex" for short), which is a sort of forumla, based on a flexible system of wildcards, that lets me identify nearly any sort of textual pattern. (A regex for the word Figure, followed by a space, one or more digits, and a colon — but only if it appears at the beginning of a line — is ^Figure [0-9]+\:.)
The best implementation of regex I've ever seen is in Nisus Software's Nisus Writer Pro (4.5 mice, $79) (a less-powerful version is found in Nisus Writer Express (3.5 mice, $45). Other apps that support regex include Bare Bones Software's TextWrangler (5.0 mice, free) and BBEdit (4.5 mice, $50), Peter Borg's Smultron (3.5 mice, $5), and Nikolai Krill's Patterns (3.5 mice, $3). You can also employ regular expressions to find files on your Mac using the grep command-line utility in Terminal. For details, see Find anything with grep.
For a quick introduction to regular expressions, see Transform HTML with regular expressions. A great way to teach yourself the ins and outs of regex is to use an interactive website that shows you matching text in real time as you change your input. Sites that do this include regexpal, RegexOne, and RegExr.
Use Boolean expressions
Continuing the theme of identifying patterns, sometimes it's not a sequence of characters or words you're looking for but rather a logical combination of terms within a file. For example, I might want to find any email message that contains the word "apple" but only if it also has a term that suggests a dessert, such as "pie," "cobbler," or "whipped cream." Whenever you're looking for a file, message, contact, or other item that contains this or that, this and that, or some other logical combination such as "(this or that) and the other thing but not something else," you want a Boolean expression.
Sign up for CIO Asia eNewsletters.