Lesson 1 of 2 Regular Expressions and Fuzzy Matching

Regular Expressions in T-SQL

This lesson explains the REGEXP functions, their flags and their platform and performance characteristics.

Learning outcomes

After completing this lesson, you will be able to:

  • Distinguish between the scalar and table-valued REGEXP functions.
  • Explain how flags and collation affect regex matching.
  • Identify the compatibility level and indexing behaviour of REGEXP_LIKE.

Why regular expressions

LIKE supports only the wildcards %, _ and simple character classes, and PATINDEX returns only a position. Many data tasks need more: validating that an email, postcode or product code has the right format, extracting all phone numbers from free text, normalizing whitespace, or splitting a string on several delimiters. Regular expressions describe such patterns with character classes (\d, [A-Z]), quantifiers (+, {3}, {2,5}), anchors (^, $), alternation (|) and capture groups ((...)).

Match the pairs

Reading a pattern

Exam skills 1.3.4

Match each regular expression element with its meaning.

Log in to try this activity Interactive activities are free with an account.

The functions

Five scalar functions and two table-valued functions are available, as the following table summarizes.

FunctionKindReturns
REGEXP_LIKE(str, pattern [, flags])Scalar (Boolean)Whether the pattern matches; usable in WHERE and CHECK
REGEXP_REPLACE(str, pattern [, replacement, start, occurrence, flags])ScalarThe string with matches replaced; \1 references a group
REGEXP_SUBSTR(str, pattern [, start, occurrence, flags, group])ScalarThe nth matching substring or capture group
REGEXP_INSTR(str, pattern [, start, occurrence, return_option, flags, group])ScalarThe start (or end) position of a match
REGEXP_COUNT(str, pattern [, start, flags])ScalarThe number of matches
REGEXP_MATCHES(str, pattern [, flags])Table-valuedOne row per match with the match and its capture groups
REGEXP_SPLIT_TO_TABLE(str, pattern [, flags])Table-valuedOne row per substring between matches
SELECT REGEXP_REPLACE(N'  Trail   Runner  2  ', '\s+', ' ')                AS Normalized,  -- ' Trail Runner 2 '
       REGEXP_SUBSTR(N'Order SO-48213 shipped', 'SO-(\d+)', 1, 1, '', 1)   AS OrderNumber, -- '48213'
       REGEXP_COUNT(N'tent, stove, tent, lamp', 'tent')                    AS TentCount;   -- 2

SELECT m.*                       -- one row per phone number found in the note
FROM Support.Ticket AS t
CROSS APPLY REGEXP_MATCHES(t.Notes, '\(?\d{3}\)?[ -]?\d{3}-\d{4}') AS m
WHERE t.TicketID = 1001;
Match the pairs

Regex functions

Exam skills 1.3.4

Match each task with the regular expression function that does it.

Log in to try this activity Interactive activities are free with an account.

Flags, collation and performance

Flags modify matching: i makes it case-insensitive, c case-sensitive (the default), m lets ^ and $ match at line breaks and s lets . match a newline; when flags contradict, the last one wins. The functions use the RE2 library's syntax, which supports most Perl-style constructs but not backreferences inside the pattern or lookarounds, and they ignore SQL collations, so a case-insensitive column collation does not make matching case-insensitive.

REGEXP_LIKE requires database compatibility level 170, while the other scalar functions work at any level. It can use an index seek only when the pattern is anchored with ^ at the start; other patterns scan. Inputs of max types are limited to 2 MB, and regex functions are not supported in natively compiled modules. The functions are available in SQL Server 2025, Azure SQL Database, SQL database in Fabric and Azure SQL Managed Instance with the SQL Server 2025 or Always-up-to-date update policy.

True or false

Flags and limits

Exam skills 1.3.4

Decide whether each statement about the regex functions is true.

Log in to try this activity Interactive activities are free with an account.
Worked example

Validating product codes

Product codes must be three uppercase letters, a hyphen and four digits, such as TNT-0042. Codes are entered by several applications, and invalid codes have caused integration failures. The database is at compatibility level 160. What should the developer do?

Raise the compatibility level to 170 and add CHECK (REGEXP_LIKE(ProductCode, '^[A-Z]{3}-\d{4}$')). The anchors make the whole value match, and the constraint enforces the rule for every application. Without the level change, REGEXP_LIKE is not available. A LIKE pattern such as '[A-Z][A-Z][A-Z]-[0-9][0-9][0-9][0-9]' works for this simple format but follows the column collation, so it may accept lowercase letters, which the regex pattern without the i flag rejects.

Check yourself

When can REGEXP_LIKE use an index seek?

Show answer

Only when the pattern is anchored at the start with ^, such as ^ABC.

Exam Tips

Remember for the exam

  • Format validation in a constraint: CHECK (REGEXP_LIKE(...)) with ^ and $ anchors.
  • REGEXP_LIKE needs compatibility level 170.
  • Every match with its groups as rows: REGEXP_MATCHES; split by a pattern: REGEXP_SPLIT_TO_TABLE.
  • Regex matching ignores collation; use the i flag for case-insensitivity.