Gmail offers some very useful search commands to help you quickly find messages that could be buried deep in your mailbox. For instance, a query like from:(John OR David) has:attachment after:2012/01/15 will locate all emails received in the past six month that have attachments and the send is either John or David.

The built-in Gmail search is powerful but there are some scenarios where it will not work. For instance, you cannot perform a wildcard search inside Gmail (like apples * red). Or how do you locate all emails that have a phone number mentioned in the message body? It is also not possible to perform case-sensitive searches inside Gmail.

You can however do all this  in Gmail with the help of regular expressions (or regex).

Gmail Search with Regular Expressions

Advanced Gmail Search with Regular Expressions

Regular expressions allow you to perform complex search operations in most popular programming languages and the same can be used with Gmail as well using Google Docs. Let’s start with a simple example.

Say you are looking for email messages that contain any variation of the string “gray color”. There could be one or more spaces between the two words, the words may use either British or American spelling and the first letters may or may not be capitalized. The regular expression thus will be:

[Gg]r(a|e)y\s.*[Cc]olou?r

Where do you put this search expression? The search box in Gmail doesn’t support regular expressions directly but with Google Docs, it can. Here’s how:

  1. Click here to make a copy of the Gmail RegEx sheet into your Google Docs account.
  2. Wait for 10-15 seconds and a new Gmail RegEx menu will appear in your new Google sheet. Choose Initialize from the menu and grant the necessary permissions as requested by the program.
  3. The program will search your entire mailbox by default but if you would like to limit the search to any particular lable (say Inbox or Spam), just put that label name in cell F3.
  4. Now enter any regular expression in the cell F4 and choose “Search Mailbox” from the Gmail RegEx menu to begin searching.

Any messages that match your search criteria will be listed in the initial columns of the same sheet. If you would like to perform a new search, simply change the regex in cell F4 and choose Search from RegEx menu again. Please do note that Google Apps Script allows you to perform 10,000 read operations in Gmail per day.

And if you are curious to know how the program works, here’s the annotated source code.