Locating specific text patterns in chaotic spreadsheets is a notoriously frustrating hurdle for data analysts. While traditional lookup functions adequately track standard funding sources, they quickly fail when confronted with inconsistent, non-standardized entries. Implementing a Regular Expression (Regex) lookup grants you the analytical power to parse complex, variable text strings with absolute precision.
Stipulation: Because native Excel formulas do not inherently support Regex, achieving this requires a custom VBA function or Power Query integration. For example, isolating specific codes like "Grant-Ref#901" within dense transaction logs becomes effortless. Below, we outline the step-by-step methods to implement these powerful custom lookup formulas.
Excel is the go-to tool for data analysis, but its traditional lookup functions-like VLOOKUP, INDEX/MATCH, and even the modern XLOOKUP-have a significant limitation: they only support basic wildcard characters (the asterisk * and question mark ?). When you need to search, match, and extract data based on complex text patterns, standard wildcard lookups quickly fall short.
This is where Regular Expressions (Regex) come in. Regex is a powerful sequence of characters that defines a search pattern, allowing you to match complex strings like email addresses, specific SKU formats, phone numbers, or dates. Historically, Excel users had to rely on complex VBA scripts to use Regex. However, with Microsoft's recent introduction of native Regex functions in Excel 365, performing a Regex lookup has become cleaner, faster, and more accessible than ever.
In this comprehensive guide, we will explore how to perform a Regex lookup in Excel using both the brand-new native Excel 365 Regex functions and the classic VBA User-Defined Function (UDF) method for older Excel versions.
If you are using Excel for Microsoft 365 (Insider or Current Channel updates), Microsoft has introduced three revolutionary functions:
REGEXTEST: Returns TRUE if a text matches a pattern, and FALSE if it does not.REGEXEXTRACT: Extracts the matching substring(s) from a text.REGEXREPLACE: Replaces matching text with a new string.To perform a lookup using Regex, we can combine the REGEXTEST function with powerful array-handling functions like FILTER or XLOOKUP.
Imagine you have a list of transactions in column A, and you want to find the first transaction that contains a standard serial number formatted as three letters, a hyphen, and four numbers (e.g., ABC-1234), and retrieve its corresponding value from Column B.
The Regex pattern for this format is: ^[A-Z]{3}-\d{4}$ (or [A-Za-z]{3}-\d{4} if case-insensitive).
To look up this pattern, you can use the following formula:
=XLOOKUP(TRUE, REGEXTEST(A2:A20, "[A-Za-z]{3}-\d{4}"), B2:B20, "No Match Found")
REGEXTEST(A2:A20, "[A-Za-z]{3}-\d{4}"): This evaluates every cell in the range A2:A20 against our Regex pattern. It returns an array of TRUE and FALSE values (e.g., {FALSE; FALSE; TRUE; FALSE; ...}).XLOOKUP(TRUE, ...): XLOOKUP searches this array of booleans for the first instance of TRUE.TRUE, it returns the corresponding value from the range B2:B20.What if you want to extract all records that match a specific pattern instead of just the first one? You can substitute XLOOKUP with the FILTER function.
For example, to filter all rows in A2:B20 where the text in Column A matches a valid email pattern:
=FILTER(A2:B20, REGEXTEST(A2:A20, "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"))
This dynamic array formula filters the entire dataset, outputting only the rows where the email format in Column A is structurally valid.
If your organization uses a version of Excel that does not support the new Microsoft 365 Regex functions, you can easily build your own custom lookup function using Visual Basic for Applications (VBA). This custom function, which we will call RegexLookup, mimics the behavior of XLOOKUP but accepts a Regex pattern as its lookup value.
ALT + F11 to open the VBA Editor.Function RegexLookup(LookupRange As Range, Pattern As String, ReturnRange As Range, Optional CaseSensitive As Boolean = False) As Variant
Dim i As Long
Dim regEx As Object
' Validate range dimensions
If LookupRange.Cells.Count <> ReturnRange.Cells.Count Then
RegexLookup = CVErr(xlErrRef)
Exit Function
End If
' Initialize regular expression object
Set regEx = CreateObject("VBScript.RegExp")
regEx.Pattern = Pattern
regEx.IgnoreCase = Not CaseSensitive
regEx.Global = False
' Loop through the search range
For i = 1 To LookupRange.Cells.Count
If regEx.Test(LookupRange.Cells(i).Value) Then
RegexLookup = ReturnRange.Cells(i).Value
Exit Function
End If
Next i
' Return #N/A error if no matches are found
RegexLookup = CVErr(xlErrNA)
End Function
The syntax for this custom function is:
=RegexLookup(lookup_range, pattern, return_range, [case_sensitive])
For example, if you want to search range A2:A100 for a product code containing "XP" followed by exactly three numbers (e.g., XP902, XP415), and retrieve its price from C2:C100, you would write:
=RegexLookup(A2:A100, "XP\d{3}", C2:C100)
To maximize the utility of your Regex lookups, here is a quick reference table of patterns you can copy and use directly inside your REGEXTEST or RegexLookup formulas:
| Target Data Type | Regex Pattern | Matches Example |
|---|---|---|
| Standard Emails | ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ |
info@company.com |
| US Phone Numbers | ^\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$ |
(123) 456-7890, 123-456-7890 |
| Dates (YYYY-MM-DD) | ^\d{4}-\d{2}-\d{2}$ |
2024-11-20 |
| IP Addresses (IPv4) | ^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$ |
192.168.1.1 |
| Alphanumeric SKU Codes | ^[A-Z]{2}-\d{3}-[A-Z]{2}$ |
US-402-NY |
By default, Regex tests look for patterns anywhere in a cell. For example, the pattern \d{3} (three consecutive digits) will return TRUE for "AB-1234-CD" because it contains "123". If you want to ensure the cell contains only your pattern and nothing else, use anchors:
^ asserts the start of the string.$ asserts the end of the string.A formula matching exactly a 3-digit cell would look like: "^\d{3}$".
If you need to look up characters that have special meanings in Regex (such as ., ?, *, +, $, ^, or parentheses), you must "escape" them using a backslash (\). For example, to search for a price containing a literal period followed by two digits (like .99), use \.99 instead of .99 (since a dot without a backslash matches any single character).
While native Excel 365 Regex functions are optimized, executing highly complex pattern matches across hundreds of thousands of rows can cause computational lag. If you experience performance issues:
A2:A1000 instead of matching the entire column A:A).Integrating Regular Expressions with Excel formulas elevates your data management capabilities. Whether you are using Excel 365's native array integration with REGEXTEST and XLOOKUP, or employing a highly versatile VBA User-Defined Function for legacy worksheets, you no longer have to compromise with restrictive, basic wildcards. By writing targeted Regex patterns, you can execute flawless, precise lookups across even the most unstructured datasets.
Disclaimer:
The documents and templates provided on this page are for informational and illustrative purposes only. They do not constitute professional, legal, or financial advice, and should not be relied upon as such. Because individual circumstances and regulatory requirements vary, these materials may not be suitable for your specific needs. We recommend consulting with a qualified professional before adapting or using any of these examples for official or commercial purposes.