Regular expressions in SQL Server 2025
27 minute read
Updated with Claude, who reran the tests on SQL Server 2025 CU7.
SQL Server 2025 brings seven REGEXP_* functions, built on the RE2 library. Since CU5, all of them accept LOBs up to 2 MB. \w and \b only know ASCII: for accented letters, use \pL. On CU7, in a serial plan, a regex uses less CPU than a LIKE in a Windows collation, but it handles parallelism poorly, and it never allows an index seek.
Version 2 - Published December 16, 2025, updated November 4, 2026 on SQL Server 2025 CU7. The performance figures of the first version were wrong for the current version; all of them were redone on CU7. Thanks to Erland Sommarskog, whose remarks started this update.
We finally have native support for regular expressions in SQL Server 2025, directly in T-SQL.
We have been waiting for this for twenty years. It removes the need for CLR assemblies and simplifies many search cases, such as validating CHECK constraints, and extracting and transforming complex data.
Native integration allows regex to be used in queries, CHECK constraints and computed columns.
Regular expressions (regex) are used to manipulate strings with complex patterns, for searching, validating and transforming text data.
Regular expressions before SQL Server 2025
Before SQL Server 2025, regular expression handling in SQL Server was very limited.
Native functions such as LIKE, PATINDEX or STRING_SPLIT offer basic search and string-splitting capabilities, but they are far from the power and flexibility of modern regex.
For example, LIKE only supports a simplified syntax with wildcard characters (%, _), and PATINDEX can only find the position of a simple pattern in a string.
To get around these limitations, the most common solution was to use custom functions through SQL CLR: you can integrate complete libraries of regex functions in CLR (.NET) as assemblies, with the deployment and security work that this implies.
Regex functions in SQL Server 2025
SQL Server 2025 provides five scalar functions and two table-valued functions (TVFs) to work with regular expressions.
Scalar functions return one value per row:
REGEXP_LIKEtests whether a string matches a pattern (boolean),REGEXP_COUNTcounts the occurrences of a pattern,REGEXP_INSTRlocates the position of a match,REGEXP_REPLACEperforms replacements, andREGEXP_SUBSTRextracts substrings.
TVFs generate row sets:
REGEXP_MATCHESdetails all the matches with their positions, whileREGEXP_SPLIT_TO_TABLEsplits a string using a pattern as the delimiter.
These functions rely on Google’s RE2 library, which guarantees an execution time linear in the size of the input, avoiding the regex denial-of-service attacks (ReDoS) that other engines allow. RE2 has no backtracking: that is what gives it this linear time, and it is also why it rejects some constructs, such as backreferences in a pattern or lookaround.
The supported platforms are SQL Server 2025 (17.x), Azure SQL Database, Azure SQL Managed Instance (with the “SQL Server 2025” or “Always-up-to-date” update policy) and SQL database in Microsoft Fabric. Fabric Data Warehouse offers the scalar functions in preview, without the two TVFs.
| Function | Type | Description | Main parameters | Returns |
|---|---|---|---|---|
REGEXP_LIKE() | Scalar | Checks whether a string matches a regex pattern | String, regex pattern, flags | Boolean, for a predicate |
REGEXP_REPLACE() | Scalar | Replaces substrings matching the pattern with a replacement string | String, regex pattern, replacement, position, occurrence, flags | Modified string |
REGEXP_SUBSTR() | Scalar | Extracts a substring matching the regex pattern | String, regex pattern, position, occurrence, flags, group | Extracted substring |
REGEXP_COUNT() | Scalar | Counts the number of occurrences of the pattern in the string | String, regex pattern, position, flags | Number of occurrences |
REGEXP_INSTR() | Scalar | Locates the position of a match | String, regex pattern, position, occurrence, return option, flags, group | Position (integer) |
REGEXP_MATCHES() | Table | Returns a table with the matching substrings and their positions | String, regex pattern, flags | Table with match details |
REGEXP_SPLIT_TO_TABLE() | Table | Splits a string into substrings according to a regex pattern | String, regex pattern, flags | Table with substrings and ordinal |
REGEXP_LIKE, REGEXP_MATCHES and REGEXP_SPLIT_TO_TABLE require compatibility level 170. Below that, REGEXP_LIKE fails with error 195 (“not a recognized built-in function name”) and the two TVFs with error 208 (“Invalid object name”). The other four scalar functions are available at every compatibility level. On Azure SQL Database and SQL database in Fabric, the database scoped configuration ALLOW_BUILTIN_TVF_IN_ALL_COMPAT_LEVELS, in preview, lifts this requirement for the TVFs; it does not exist in SQL Server 2025. To check or change the compatibility level:
USE PachaDataFormation;
-- Check the current level in the current database
SELECT compatibility_level
FROM sys.databases
WHERE name = DB_NAME();
-- Change it if needed
ALTER DATABASE PachaDataFormation
SET COMPATIBILITY_LEVEL = 170;
Restrictions
- Since CU5 (May 2026), all
REGEXP_*functions accept LOBs (varchar(max)andnvarchar(max)), with a limit of 2 MB per string. Before that, the documentation reserved LOBs forREGEXP_LIKE,REGEXP_COUNTandREGEXP_INSTR. The 2 MB (2,097,152 bytes) are counted on the string converted to UTF-8, not on its stored size: annvarchar(max)of 2 million ASCII characters passes although it takes 4 MB, and avarchar(max)of a million accented letters fails although it takes only one. Beyond that, the call fails with error 19311 (“The input for ‘string_expression’ exceeds the maximum allowed size of 2MB”). - Natively compiled stored procedures (In-Memory OLTP) cannot call regex functions.
- Regex functions do not follow the collation of the column: the comparison is done on Unicode characters and the pattern, not on linguistic rules. A case-insensitive search is requested with the
'i'flag, and nothing makes a regex accent-insensitive:REGEXP_LIKE(N'e', 'é', 'i')is false. - A filtered index does not accept a regex in its
WHEREclause, whose grammar only allows simple comparisons:REGEXP_LIKEfails there with syntax error 156, likeLIKE, andREGEXP_COUNT(...) > 0with error 10735, like any function. A persisted computed column, on the other hand, can call a regex and be indexed (see below). - The maximum pattern length is 8,000 bytes. Repetitions with explicit quantifiers
{n},{n,m},{n,}are limited to 1,000 (a{1001}fails with error 19300, “invalid repetition size”). - RE2 supports neither lookahead (
(?=...)) nor lookbehind ((?<=...)).
For example, the following query fails because it uses a lookbehind:
USE PachaDataFormation;
SELECT Nom,
CONCAT(UPPER(REGEXP_SUBSTR(Nom, '^\pL')),
LOWER(REGEXP_SUBSTR(Nom, '(?<=^\pL).+'))) AS InitCap
FROM Contact.Contact;
The error message is:
Msg 19300, Level 16, State 1, Line 3
An invalid Pattern '(?<=^\pL).+' was provided. Error 'invalid perl operator: (?<' occurred during evaluation of the Pattern.
Accented letters, \w and \b
In RE2, the Perl classes \d, \s and \w, the word boundary \b and the POSIX classes such as [[:alpha:]] only know ASCII. \w is [0-9A-Za-z_], and \b is a boundary between a \w character and another character. For French text, this is a trap: an accented letter is not a word character.
SELECT
IIF(REGEXP_LIKE(N'résumé', '^\w+$'), 1, 0) AS AvecW, -- 0
IIF(REGEXP_LIKE(N'résumé', '^[[:alpha:]]+$'), 1, 0) AS AvecPosix, -- 0
IIF(REGEXP_LIKE(N'résumé', '^\pL+$'), 1, 0) AS AvecPL; -- 1
-- \w stops at the first accented letter
SELECT
REGEXP_SUBSTR(N'Hélène', '\w+') AS AvecW, -- H
REGEXP_SUBSTR(N'Hélène', '\pL+') AS AvecPL; -- Hélène
RE2 knows the Unicode classes: \pL means a letter of any script, \PL anything that is not a letter, \pN a numeric character in the Unicode sense (including ² and ½; \p{Nd} for decimal digits only), \p{Greek} a Greek character. They also work on a varchar column.
To replace \b, the safest form is (^|\PL) before the word and (\PL|$) after it, retrieving the word through its capture group. For a number, (^|\D) and (\D|$) play the same role. All the examples in this article are written that way. Since these groups consume the character that separates two words, they suit REGEXP_SUBSTR, but can miss an occurrence stuck to the previous one in REGEXP_COUNT or REGEXP_REPLACE: REGEXP_COUNT(N'été été', '(^|\PL)été(\PL|$)') returns 1.
In the demo database, 1,812 of the 120,140 names in Contact.Contact contain a letter outside [A-Za-z], most often an accented one. A validation written ^[\w\s'-]+$ rejects all of them, while ^[\pL\s'-]+$ accepts them.
REGEXP_LIKE
REGEXP_LIKE tests whether a string matches a pattern. Its full syntax is:
REGEXP_LIKE ( string_expression, pattern_expression [ , flags ] )
The string_expression parameter accepts the types char, nchar, varchar or nvarchar, LOBs included up to 2 MB. The pattern_expression defines the regex pattern, with a limit of 8,000 bytes. The optional flags parameter (30 characters at most) controls the matching behavior (for example case insensitivity). The function returns a boolean, like a classic LIKE, and is therefore used in a predicate: WHERE, CASE WHEN or IIF.
REGEXP_LIKE requires compatibility level 170.
USE PachaDataFormation;
-- Email validation
SELECT
ContactId,
Email,
CASE
WHEN REGEXP_LIKE(Email, '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}$')
THEN 'Email valide'
ELSE 'Email invalide'
END AS ValidationEmail
FROM Contact.Contact
WHERE Email IS NOT NULL
ORDER BY ContactId;
-- Filter the names containing anything other than letters, spaces,
-- apostrophes and hyphens
SELECT
ContactId,
Prenom,
Nom
FROM Contact.Contact
WHERE REGEXP_LIKE(Nom, '[^\pL\s''-]');
-- None in the demo database
Using it in a CHECK constraint guarantees data integrity on insert. The example creates a temporary table so as not to modify the demo database:
USE PachaDataFormation;
CREATE TABLE #Prospect (
ProspectId int IDENTITY PRIMARY KEY,
Email varchar(150) NOT NULL
CONSTRAINT ck_Prospect_Email CHECK (REGEXP_LIKE(Email, '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$')),
Telephone varchar(15) NULL
CONSTRAINT ck_Prospect_Telephone CHECK (REGEXP_LIKE(Telephone, '^0[1-9]([\s.-]?\d{2}){4}$'))
);
INSERT INTO #Prospect (Email, Telephone) VALUES ('j.garcia@exemple.fr', '04 35 93 56 88'); -- accepted
INSERT INTO #Prospect (Email, Telephone) VALUES ('pas un email', NULL); -- rejected, error 547
DROP TABLE #Prospect;
REGEXP_REPLACE
REGEXP_REPLACE offers advanced replacement capabilities with support for capture groups. Its full syntax:
REGEXP_REPLACE ( string_expression, pattern_expression
[ , string_replacement [ , start [ , occurrence [ , flags ] ] ] ] )
The string_replacement parameter defines the substitution string (empty by default). The start parameter gives the starting position (1 by default). The occurrence parameter says which occurrence to replace: 0, the default, replaces all occurrences, while a positive integer targets only the Nth occurrence.
The replacement string accepts backreferences: \1 to \9 insert the text captured by the matching group, and \& inserts the whole match. Microsoft’s documentation writes & without a backslash, but on CU7 a lone & stays a literal character: REGEXP_REPLACE('123-456', '\d+', '[&]') returns [&]-[&], and '[\&]' returns [123]-[456]. Before a digit or &, a literal backslash is doubled: '\\1' returns \1.
USE PachaDataFormation;
-- Formatting a phone number with capture groups
SELECT TOP (10)
Telephone,
REGEXP_REPLACE(Telephone, '^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$', '\1 \2 \3 \4 \5') AS TelephoneFormate
FROM Contact.Contact
WHERE Telephone IS NOT NULL;
-- 0435935688 becomes 04 35 93 56 88
-- Masking the last four digits
SELECT TOP (10)
Telephone,
REGEXP_REPLACE(Telephone, '\d{4}$', '****') AS TelephoneMasque
FROM Contact.Contact
WHERE Telephone IS NOT NULL;
-- Replacing the second occurrence only
SELECT REGEXP_REPLACE('A-B-C-D', '-', '/', 1, 2) AS Resultat;
-- Result: A-B/C-D
-- Putting each number between brackets with \&
SELECT REGEXP_REPLACE('Salle 12, étage 3', '\d+', '[\&]') AS Resultat;
-- Result: Salle [12], étage [3]
-- Removing all non-numeric characters
SELECT TOP (10)
Tel,
REGEXP_REPLACE(Tel, '[^0-9]', '') AS TelNettoye
FROM Contact.ProspectUS;
-- 712283-6281 becomes 7122836281
REGEXP_SUBSTR
REGEXP_SUBSTR extracts the part of a string that matches the pattern. It works at any compatibility level.
REGEXP_SUBSTR ( string_expression, pattern_expression
[ , start [ , occurrence [ , flags [ , group ] ] ] ] )
The group parameter extracts a capture group: 0 returns the whole match (the default), a positive integer returns the Nth captured group.
USE PachaDataFormation;
-- Extract the user name and the domain from an email
SELECT
ContactId,
Email,
REGEXP_SUBSTR(Email, '^[^@]+') AS NomUtilisateur,
REGEXP_SUBSTR(Email, '@(.+)$', 1, 1, '', 1) AS Domaine
FROM Contact.Contact
WHERE Email IS NOT NULL;
-- Extracting the first name and the last name separately
DECLARE @Nom nvarchar(50) = N'Hélène D''Arco';
SELECT @Nom,
REGEXP_SUBSTR(@Nom, '\pL+', 1, 1) AS Prenom, -- Hélène
REGEXP_SUBSTR(@Nom, '[\pL'']+', 1, 2) AS Nom; -- D'Arco
-- With \w+, the extracted first name would be "H"
-- Extracting a French postal code: five digits that are
-- neither preceded nor followed by a digit (group 2)
DECLARE @Adresse varchar(50) = '55 AVENUE MARECHAL FOCH 69006 LYON';
SELECT REGEXP_SUBSTR(@Adresse, '(^|\D)(\d{5})(\D|$)', 1, 1, '', 2) AS CodePostal;
-- Result: 69006
-- First word starting with a vowel (group 2)
SELECT
Titre,
REGEXP_SUBSTR(PhraseSynthese, '(^|\PL)([aeiouyàâéèêëîïôûù]\pL*)', 1, 1, 'i', 2) AS Mot
FROM Stage.StageLangue
WHERE LangueCd = 'FR';
REGEXP_COUNT
REGEXP_COUNT counts the number of matches of a pattern in a string:
REGEXP_COUNT ( string_expression, pattern_expression [ , start [ , flags ] ] )
It accepts LOBs up to 2 MB and returns an integer.
USE PachaDataFormation;
-- Count the digits of an amount
SELECT TOP (10)
MontantHT,
REGEXP_COUNT(CAST(MontantHT AS varchar(50)), '\d') AS NombreChiffres
FROM Inscription.Facture;
-- Count the words of the evaluation comments
SELECT TOP (10)
Texte,
REGEXP_COUNT(Texte, '\pL+') AS NombreMots,
REGEXP_COUNT(Texte, '\w+') AS NombreMotsW -- wrong as soon as an accented letter splits a word
FROM Inscription.Reponse
WHERE Texte IS NOT NULL;
-- Count the objectives of a course, separated by semicolons
SELECT
Titre,
REGEXP_COUNT(Objectifs, ';') + 1 AS NombreObjectifs
FROM Stage.StageLangue
WHERE LangueCd = 'FR' AND Objectifs IS NOT NULL;
On “Peut-être un peu plus de questions en fin de journée.”, \pL+ counts 11 words, and \w+ counts 12, because “journée” is split into “journ” and “e”.
REGEXP_INSTR
REGEXP_INSTR returns the position of a match, with fine control over the result:
REGEXP_INSTR ( string_expression, pattern_expression
[ , start [ , occurrence [ , return_option [ , flags [ , group ] ] ] ] ] )
The return_option parameter determines whether the function returns the position of the start of the match (0, the default) or the position of the character that follows it (1): REGEXP_INSTR('abcdef', 'cd', 1, 1, 1) returns 5.
USE PachaDataFormation;
-- Find the position of the at sign and of the domain in the email
SELECT
ContactId,
Email,
REGEXP_INSTR(Email, '@') AS PositionArobase,
REGEXP_INSTR(Email, '@', 1, 1, 1) AS PositionDomaine
FROM Contact.Contact
WHERE Email IS NOT NULL;
-- Position of the spaces in full names
SELECT
ContactId,
CONCAT(Prenom, ' ', Nom) AS NomComplet,
REGEXP_INSTR(CONCAT(Prenom, ' ', Nom), '\s') AS PremierEspace,
REGEXP_INSTR(CONCAT(Prenom, ' ', Nom), '\s', 1, 2) AS DeuxiemeEspace
FROM Contact.Contact
WHERE Prenom IS NOT NULL;
REGEXP_MATCHES
REGEXP_MATCHES returns a table with the details of each match:
REGEXP_MATCHES ( string_expression, pattern_expression [ , flags ] )
The returned table contains the columns match_id (sequence), start_position, end_position, match_value (same type as the input), and substring_matches (a JSON document detailing the capture groups).
USE PachaDataFormation;
-- Extract all the hashtags of a text
SELECT *
FROM REGEXP_MATCHES(
N'Découvrez #SQLServer2025 et les #Regex pour #DataProcessing',
'#([A-Za-z0-9_]+)'
);
-- Three rows; for the first one, substring_matches is
-- [{"value":"SQLServer2025","start":12,"length":13}]
-- Using CROSS APPLY on a table: the version numbers
-- mentioned in the course titles
SELECT S.StageId, S.Titre, M.match_id, M.match_value
FROM Stage.StageLangue AS S
CROSS APPLY REGEXP_MATCHES(S.Titre, '\d+(\.\d+)*') AS M
WHERE S.LangueCd = 'FR';
REGEXP_SPLIT_TO_TABLE
REGEXP_SPLIT_TO_TABLE splits a string into rows according to a delimiter pattern:
REGEXP_SPLIT_TO_TABLE ( string_expression, pattern_expression [ , flags ] )
The returned table contains value (the substring) and ordinal (its position, starting at 1).
USE PachaDataFormation;
-- Split a list of skills
SELECT *
FROM REGEXP_SPLIT_TO_TABLE('SQL, Python, Java, JavaScript', ',\s*');
-- Returns: SQL (1), Python (2), Java (3), JavaScript (4)
-- Split a text into words
SELECT value, ordinal
FROM REGEXP_SPLIT_TO_TABLE('Le chat mange la souris', '\s+');
-- Using it with a table: one course objective per row
SELECT S.StageId, O.ordinal, O.value AS Objectif
FROM Stage.StageLangue AS S
CROSS APPLY REGEXP_SPLIT_TO_TABLE(S.Objectifs, '\s*;\s*') AS O
WHERE S.LangueCd = 'FR';
These two TVFs require compatibility level 170.
The RE2 syntax
Metacharacters and character classes
The RE2 engine supports the standard metacharacters: . matches any character except the line break, ^ anchors at the start, $ anchors at the end, \ escapes special characters, | is alternation (logical or), and square brackets [] define character classes.
The Perl shortcuts only cover ASCII: \d is equivalent to [0-9], \D to [^0-9], \s to white space ([\t\n\f\r ]: space, tab, line feed, carriage return, form feed), \S to its opposite, \w to [0-9A-Za-z_], and \W to its opposite.
POSIX classes are also limited to ASCII: [[:alnum:]] for [0-9A-Za-z], [[:alpha:]] for [A-Za-z], [[:digit:]] for digits, [[:lower:]] and [[:upper:]] for unaccented lowercase and uppercase letters, [[:space:]] for white space, [[:word:]] for [0-9A-Za-z_], and [[:xdigit:]] for hexadecimal digits.
Unicode classes are the only ones that know accented letters: \pL (letter), \pN (numeric character, including ² and ½), \p{Greek} (Greek script), and their opposites \PL, \PN, \P{Greek}.
Quantifiers
Quantifiers control repetitions: * means zero or more, + one or more, ? zero or one, {n} exactly n occurrences, {n,m} between n and m, {n,} n or more. The lazy versions add a ?: *?, +?, ??, {n,m}?. They keep the shortest match instead of the longest. They are not cheaper for that, since RE2 does no backtracking.
The quantifiers {n}, {n,m} and {n,} are limited to 1,000 repetitions. The quantifiers * and + have no such restriction.
Groups and references
Parentheses create numbered capture groups: (pattern). Non-capturing groups (?:pattern) group without capturing. Named groups (?P<name>pattern) improve readability, and remain numbered. A backreference inside a pattern does not exist in RE2; \1 to \9 are only used in the replacement string of REGEXP_REPLACE.
Anchors and word boundaries
Anchors position the match: ^ start of string (or of line with the m flag), $ end of string (or of line), \A absolute start of string, \z absolute end, \b ASCII word boundary, \B its opposite. For a word boundary in accented text, use (^|\PL) and (\PL|$).
Flags
| Flag | Description | Default |
|---|---|---|
c | Case-sensitive matching | On |
i | Case-insensitive matching | Off |
m | Multiline mode: ^ and $ also match the starts and ends of lines | Off |
s | . also matches line breaks | Off |
Flags combine in a string: 'im' enables case insensitivity and multiline mode. With contradictory flags, the last one wins: REGEXP_LIKE('ABC', 'abc', 'ic') is false, REGEXP_LIKE('ABC', 'abc', 'ci') is true.
USE PachaDataFormation;
-- Case-insensitive search
SELECT ContactId, Prenom, Nom
FROM Contact.Contact
WHERE REGEXP_LIKE(Nom, 'simon', 'i');
-- Multiline mode: remove the spaces and tabs at the start of each line
DECLARE @Texte varchar(100) = ' ligne 1' + CHAR(10) + ' ligne 2';
SELECT REGEXP_REPLACE(@Texte, '^[ \t]+', '', 1, 0, 'm') AS TexteNettoye;
-- Combining flags: lines that start with the word "le"
DECLARE @Lignes nvarchar(100) = N'Leçon utile' + CHAR(10) + N'le rythme' + CHAR(10) + N'Le support';
SELECT REGEXP_COUNT(@Lignes, '^le(\PL|$)', 1, 'im') AS NombreLignes;
-- Result: 2. Without the m flag: 0. With '^le\b': 3, "Leçon" included
The examples work on variables: the evaluation answers in the demo database all fit on a single line. In '^[ \t]+', it is better to avoid \s, which contains the line break: with the m flag, '^\s+' would also remove empty lines.
Practical examples
Email address validation
USE PachaDataFormation;
-- Email pattern with a top-level domain check
DECLARE @MotifEmail varchar(200) = '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$';
-- Filter the valid emails
SELECT ContactId, Email
FROM Contact.Contact
WHERE REGEXP_LIKE(Email, @MotifEmail, 'i');
-- Data quality report
SELECT
COUNT(Email) AS TotalEmails,
SUM(IIF(REGEXP_LIKE(Email, @MotifEmail, 'i'), 1, 0)) AS EmailsValides,
SUM(IIF(NOT REGEXP_LIKE(Email, @MotifEmail, 'i'), 1, 0)) AS EmailsInvalides
FROM Contact.Contact;
French phone number validation
USE PachaDataFormation;
-- French landline or mobile phone: 10 digits starting with 0,
-- optionally separated by spaces, dots or hyphens
DECLARE @MotifTelFR varchar(100) = '^0[1-9]([\s.-]?\d{2}){4}$';
SELECT Telephone,
IIF(REGEXP_LIKE(Telephone, @MotifTelFR), 'Valide', 'Invalide') AS Statut
FROM Contact.Contact
WHERE Telephone IS NOT NULL;
-- Normalization (keep only the digits)
SELECT Telephone,
REGEXP_REPLACE(Telephone, '[^0-9]', '') AS TelephoneNormalise
FROM Contact.Contact
WHERE REGEXP_LIKE(Telephone, '\d');
Postal code and SIREN validation
USE PachaDataFormation;
-- French postal code: 5 digits, from 01 to 95 followed by 3 digits,
-- or overseas (971 to 976, 984, 986 to 989) followed by 2 digits
DECLARE @MotifCP varchar(60) = '^((0[1-9]|[1-8]\d|9[0-5])\d{3}|(97[1-6]|98[46-9])\d{2})$';
SELECT
v.NomVille,
v.CodePostal,
IIF(REGEXP_LIKE(v.CodePostal, @MotifCP), 'Valide', 'Invalide') AS StatutCP
FROM Reference.ville AS v
WHERE v.PaysCD = 'FRA';
-- 3,130 codes come out invalid: those of departments 01 to 09, stored without the leading zero (1400)
-- SIREN: 9 digits, after removing spaces, dots and hyphens
SELECT SocieteId, Nom, Siren
FROM Contact.Societe
WHERE NOT REGEXP_LIKE(REGEXP_REPLACE(Siren, '[\s.-]', ''), '^\d{9}$');
-- No rows: the 1,379 SIREN numbers filled in the database are valid
Data cleaning and transformation
USE PachaDataFormation;
-- Reduce multiple spaces to a single one
SELECT Texte, REGEXP_REPLACE(Texte, '\s+', ' ') AS TexteNettoye
FROM Inscription.Reponse
WHERE REGEXP_LIKE(Texte, '\s{2,}');
-- No answer in the demo database contains any
-- Extracting structured data from free text
SELECT Texte,
REGEXP_SUBSTR(Texte, '(^|\D)(\d{1,2}h\d{2})(\D|$)', 1, 1, '', 2) AS Heure,
REGEXP_SUBSTR(Texte, '(^|\D)(\d+)\s*minutes', 1, 1, 'i', 2) AS Minutes,
REGEXP_SUBSTR(Texte, 'chapitre\s+(\d+)', 1, 1, 'i', 1) AS Chapitre
FROM Inscription.Reponse
WHERE REGEXP_LIKE(Texte, '\d');
Masking sensitive data
USE PachaDataFormation;
-- Partial masking of emails: first two characters and domain
SELECT Email,
REGEXP_REPLACE(Email, '^(.{2})(.*)(@.+)$', '\1***\3') AS EmailMasque
FROM Contact.Contact
WHERE Email IS NOT NULL;
-- Masking a phone number, keeping the first two and the last two digits
SELECT Telephone,
REGEXP_REPLACE(Telephone, '^(\d{2})\d{6}(\d{2})$', '\1 XX XX XX \2') AS TelephoneMasque
FROM Contact.Contact
WHERE Telephone IS NOT NULL;
A masking rule must account for what its pattern does not recognize: a number that does not have exactly ten digits comes out in the clear. In the demo database, that is the case for 19,220 numbers out of 98,371.
Performance analysis
The test bench
The first version of this article compared LIKE and REGEXP_LIKE on the Posts table of the StackOverflow2013 database, and concluded that the regex was 15 to 31 times slower. Those measurements were made with a degree of parallelism of 2, on a version earlier than CU7. Yet degree 2 is precisely the one where the duration of a regex is worst (see below).
I redid the measurements on SQL Server 2025 CU7 (17.0.4065.4), Enterprise Developer Edition, in a Linux container on a laptop (Intel Core Ultra 7 155H, 22 logical processors). The PachaDataFormation database contains four copies of a table of one million prospects, which differ only by the type and collation of the columns. Each figure is the median CPU time of three executions, with data in cache, after one warm-up execution, and in a serial plan (MAXDOP 1), except in the section on parallelism. Reading the table without filtering anything costs about 85 ms of CPU.
USE PachaDataFormation;
SELECT COUNT(*)
FROM Contact.ProspectUS
WHERE Email LIKE '%hotmail%'
OPTION (MAXDOP 1);
SELECT COUNT(*)
FROM Contact.ProspectUS
WHERE REGEXP_LIKE(Email, 'hotmail', 'i')
OPTION (MAXDOP 1);
Both queries find the same 75,242 rows.
Collation
| Table | Type and collation of Email | LIKE '%hotmail%' | REGEXP_LIKE | REGEXP_LIKE ... 'i' |
|---|---|---|---|---|
Contact.ProspectUS | varchar(100), French_CI_AS | 954 ms | 697 ms | 704 ms |
Contact.ProspectUS_N | nvarchar(100), French_CI_AS | 975 ms | 571 ms | |
Contact.ProspectUS_MAX | varchar(max), French_CI_AS | 1,105 ms | 857 ms | |
Contact.ProspectUS_SQL_Latin1 | varchar(100), SQL_Latin1_General_CP1_CI_AS | 125 ms | 738 ms |
In a Windows collation (French_CI_AS), the regex costs 20% to 40% less CPU than LIKE. The 'i' flag costs almost nothing. In a SQL collation on varchar, on the other hand, LIKE is six times cheaper than the regex.
LIKE compares according to the rules of the collation, character by character, and a Windows collation applies the linguistic rules of Unicode, even to a varchar column. A SQL collation on varchar compares characters with a simple sort table, much cheaper. The regex ignores the collation and compares characters according to their Unicode properties: its cost depends on the length of the string and of the pattern, not on the collation.
String length
The gap grows with the length of the strings. On 200,000 rows, I compared the email address alone (23 characters on average, pattern hotmail) with the address followed by a space and repeated twenty times (480 characters), with a pattern absent from every row:
| Column | LIKE | REGEXP_LIKE ... 'i' |
|---|---|---|
23 characters, varchar, French_CI_AS | 241 ms | 193 ms |
480 characters, varchar, French_CI_AS | 3,289 ms | 340 ms |
480 characters, nvarchar, French_CI_AS | 3,317 ms | 275 ms |
480 characters, varchar, SQL_Latin1_General_CP1_CI_AS | 228 ms | 336 ms |
On long strings in a Windows collation, the regex is ten times cheaper than LIKE. In a SQL collation, LIKE stays ahead.
Parallelism
This is the weak point I found on CU7. The same search, on the same table of one million rows, at different degrees of parallelism (one execution after the warm-up):
MAXDOP | LIKE CPU | LIKE duration | REGEXP_LIKE ... 'i' CPU | REGEXP_LIKE ... 'i' duration |
|---|---|---|---|---|
| 1 | 985 ms | 986 ms | 731 ms | 733 ms |
| 2 | 990 ms | 493 ms | 5,887 ms | 2,998 ms |
| 4 | 1,067 ms | 267 ms | 1,333 ms | 341 ms |
| 8 | 1,234 ms | 163 ms | 2,218 ms | 287 ms |
| 16 | 1,664 ms | 115 ms | 6,749 ms | 443 ms |
| 22 | 2,165 ms | 110 ms | 10,787 ms | 529 ms |
LIKE parallelizes as expected: total CPU rises a little, duration drops. The regex consumes more and more CPU as the number of threads grows, fifteen times more at DOP 22 than in a serial plan, and its duration goes back up beyond DOP 8. The DOP 2 case is the strangest: eight times more CPU than in a serial plan, and a query four times slower than in a serial plan. The same anomaly appeared once at DOP 3 and once at DOP 4, without reproducing on the next execution. At DOP 2, I reproduced it on every execution, with REGEXP_LIKE as with REGEXP_COUNT, and on another table (Elearning.Activite, 7.8 million rows: 5.5 seconds in a serial plan, 22 seconds at DOP 2, 1.2 seconds at DOP 8). During these executions, the session accumulates CMEMTHREAD waits, which signal contention on a memory object shared between threads; LIKE produces none.
I have no explanation, and I only measured on this Linux container. In practice, do not assume that a regex-based query benefits from parallelism, and measure it at several MAXDOP values. In my demo database, the MAXDOP database scoped configuration is 2, and that is exactly the degree the plan chose by default.
Cardinality estimation
A major problem with regular expressions is cardinality estimation. The optimizer has no statistical model for a regex: how do you estimate the number of rows that match an arbitrary pattern?
For a LIKE, the optimizer relies on the string summary of the column statistics (see SQL Server string statistics), and the result is rather good. On Contact.ProspectUS, LIKE '%hotmail%' is estimated at 74,690 rows, against 75,242 actual.
REGEXP_LIKE is estimated at 90,000 rows, or 9% of the table, whatever the pattern: 'hotmail', 'hotmail' with 'i', or a more selective pattern such as '^[a-z]+\d+@gmail\.com$'. The optimizer uses a fixed percentage. Here the gap is small because hotmail concerns 7.5% of the rows; with a pattern that keeps 0.1% of them, the estimate would be nearly a hundred times too high, which can rule out an index or inflate a memory grant for a sort or a hash.
The CPU cost estimate of the scan is also the same with or without a regex: the optimizer does not know what evaluating the pattern costs.
The documentation of REGEXP_LIKE says that cardinality estimation feedback (CE feedback, which requires Query Store) detects poorly estimated REGEXP_LIKE queries and applies one of the two options presented below by itself; trace flag 16268 disables this behavior. I did not measure it, and it only corrects after several executions.
Query hints for cardinality estimation
To manually correct large estimation errors, SQL Server offers two query hints:
USE PachaDataFormation;
SELECT COUNT(*)
FROM Contact.ProspectUS
WHERE REGEXP_LIKE(Email, 'hotmail')
OPTION (USE HINT ('ASSUME_FIXED_MIN_SELECTIVITY_FOR_REGEXP'));
SELECT COUNT(*)
FROM Contact.ProspectUS
WHERE REGEXP_LIKE(Email, 'hotmail')
OPTION (USE HINT ('ASSUME_FIXED_MAX_SELECTIVITY_FOR_REGEXP'));
ASSUME_FIXED_MIN_SELECTIVITY_FOR_REGEXP gives an estimate of 5,000 rows, or 0.5% of the table. ASSUME_FIXED_MAX_SELECTIVITY_FOR_REGEXP gives 500,000 rows, or 50%. These hints do not make the estimate right, but they let you pick the right order of magnitude when you know it.
Pattern complexity
Three email validation patterns, of increasing precision, on the million rows of Contact.ProspectUS:
USE PachaDataFormation;
-- Common pattern
SELECT COUNT(*)
FROM Contact.ProspectUS
WHERE REGEXP_LIKE(Email, '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}$')
OPTION (MAXDOP 1);
-- Looser
SELECT COUNT(*)
FROM Contact.ProspectUS
WHERE REGEXP_LIKE(Email, '^[^\s@]+@[^\s@]+\.[^\s@]{2,}$')
OPTION (MAXDOP 1);
-- Stricter, with bounded lengths
SELECT COUNT(*)
FROM Contact.ProspectUS
WHERE REGEXP_LIKE(Email, '^[A-Za-z0-9][A-Za-z0-9._%+-]{0,63}@[A-Za-z0-9][A-Za-z0-9.-]{0,62}\.[A-Za-z]{2,6}$')
OPTION (MAXDOP 1);
The common pattern consumes 933 ms of CPU, the looser one 873 ms, the stricter one 1,011 ms. The complexity of the pattern has a real but modest effect: about fifteen percent between the extremes. RE2 compiles the pattern into an automaton, and the cost depends mostly on the number of characters read.
SARGability of regular expressions
A regex anchored at the start, like ^Fera, looks for strings that start with Fera, like LIKE 'Fera%' apart from case. You might therefore hope for an index seek.
USE PachaDataFormation;
-- Index nix_contact_nom on Contact.Contact (Nom)
SELECT ContactId
FROM Contact.Contact
WHERE Nom LIKE 'Fera%';
SELECT ContactId
FROM Contact.Contact
WHERE REGEXP_LIKE(Nom, '^Fera');
The LIKE gives an Index Seek on nix_contact_nom:
LIKE 'Fera%': seek in the nix_contact_nom index. Download the plan (plan-like-prefixe.sqlplan)The regex gives an Index Scan of the same index, estimated at 10,813 rows (9%) for 22 actual:
REGEXP_LIKE(Nom, '^Fera'): full scan of the index. Download the plan (plan-regexp-prefixe.sqlplan)Neither the 'm' flag, nor the 's' flag, nor the ASSUME_FIXED_MIN_SELECTIVITY_FOR_REGEXP hint changes the plan, and a WITH (FORCESEEK) makes the query fail (error 8622, the optimizer finds no plan). In the first version of this article, I had also tried columns in a binary collation and in a case-sensitive UTF-8 collation, with no more success.
A seek reads a range of the index, in the order of its collation, while the regex ignores the collation. Extra rows in the range would not be a problem: a residual predicate would eliminate them, like the one the LIKE plan already applies after its seek. The risk is the opposite. With some collations, strings that start with the same characters do not follow each other in sort order. In Czech (Czech_CI_AS), “ch” is a letter sorted after “h”: chata is placed after hrad, outside the range of names in “c”, while REGEXP_LIKE(Nom, '^c') must return it. A seek would miss rows, and the same query would not return the same result with or without the index. The documentation warns that regex can behave differently from LIKE, “especially on indexed columns with language-specific collations”.
The page for REGEXP_LIKE nevertheless states, since September 2026, that the function is SARGable when the pattern starts with ^, and that the optimizer can then perform a seek. On CU7, I got none in any collation, including on the example of that page.
Optimization strategies
Prefiltering with LIKE
It is often recommended to reduce the volume before applying the regex, with a simpler LIKE:
USE PachaDataFormation;
-- Regex alone
SELECT COUNT(*)
FROM Contact.ProspectUS
WHERE REGEXP_LIKE(Email, '^[a-z]+\d+@gmail\.com$', 'i')
OPTION (MAXDOP 1);
-- Prefiltering with LIKE, then regex
SELECT COUNT(*)
FROM Contact.ProspectUS
WHERE Email LIKE '%@gmail.com'
AND REGEXP_LIKE(Email, '^[a-z]+\d+@gmail\.com$', 'i')
OPTION (MAXDOP 1);
On CU7, this LIKE filters nothing. The plan shows that the optimizer evaluates the regex first: the predicate of the scan is regexp_like(...) AND [Email] like '%@gmail.com'. The two queries therefore cost about the same (814 and 876 ms of CPU in French_CI_AS, around 800 ms in a SQL collation).
To force the order, you need a CASE:
USE PachaDataFormation;
SELECT COUNT(*)
FROM Contact.ProspectUS_SQL_Latin1
WHERE CASE WHEN Email LIKE '%@gmail.com'
THEN CASE WHEN REGEXP_LIKE(Email, '^[a-z]+\d+@gmail\.com$', 'i') THEN 1 END
END = 1
OPTION (MAXDOP 1);
In a SQL collation on varchar, where the LIKE costs little, forced prefiltering takes the query from about 770 to 460 ms of CPU. In French_CI_AS, where the LIKE costs more than the regex, it takes it from 790 to 1,350 ms. Prefiltering is only worthwhile if the filter is cheaper than the regex, or if it allows a seek, for example with a LIKE 'prefix%' on an indexed column.
Persisting results for frequent validations
A persisted computed column can call a regex, and be indexed. For a validation that is used often, computing the result once at write time avoids recomputing it on every read. The example works on a temporary copy of the table:
USE PachaDataFormation;
SELECT ContactId, Email
INTO #ContactEmail
FROM Contact.Contact;
-- Persisted computed column
ALTER TABLE #ContactEmail ADD EmailValide AS (
CAST(IIF(REGEXP_LIKE(Email, '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$'), 1, 0) AS bit)
) PERSISTED;
-- Index on the persisted column
CREATE INDEX ix_ContactEmail_EmailValide ON #ContactEmail (EmailValide);
SELECT ContactId, Email
FROM #ContactEmail
WHERE EmailValide = 0;
DROP TABLE #ContactEmail;
As with any index on a computed column, the session must have the required SET options, QUOTED_IDENTIFIER set to ON in particular. This is the case in SSMS, but not in sqlcmd without the -I option, where the ALTER TABLE fails with error 1934.
Pattern design rules
- Anchor patterns with
^and$when the meaning requires it. This affects correctness, not much speed: on the email addresses,'^zzz'costs about 5% less CPU than'zzz', and'zzz$'as much as'zzz'. - Write
\pLrather than\w, and(^|\PL)/(\PL|$)rather than\b, as soon as the text can contain accented letters. - Do not count on lazy quantifiers (
*?,+?) to save time: RE2 does no backtracking, so they only change which match is kept. - Prefer a regex to
LIKEon a column in a Windows collation when the query runs in a serial plan, and keepLIKEon avarcharin a SQL collation, when it allows a seek, or as soon as the query is parallel.
Measuring CPU impact
To evaluate the CPU impact of regex, enable time statistics before running the query, and compare several degrees of parallelism:
USE PachaDataFormation;
SET STATISTICS TIME ON;
SELECT COUNT(*)
FROM Contact.ProspectUS
WHERE REGEXP_LIKE(Email, 'hotmail', 'i')
OPTION (MAXDOP 1);
SELECT COUNT(*)
FROM Contact.ProspectUS
WHERE REGEXP_LIKE(Email, 'hotmail', 'i')
OPTION (MAXDOP 4);
SET STATISTICS TIME OFF;