TSQL Regular Expression Workbench

Comments 30

Share to social media

This Workbench is about using Regular expressions with SQL Server via TSQL. It doesn’t even attempt to teach how regular expressions work or how to pull them together. There are plenty of such resources on the Web. The aim is to demonstrate a few possibilities and try to persuade you to experiment with them if you don’t already use Regex with SQL Server.

We suggest that, if you are an ordinary mortal like Phil or I, without special powers, you should use an application such as RegexBuddy to form, edit and interpret Regular expressions. It makes learning them a lot easier. In order that people with access only to SQL Server 2000 can use the workbench, we’ll use OLE in the examples, but they are readily adapted to CLR. As always, the source code is available to download at the bottom of the article.


  1. Introduction
  2. The OLE Functions
    1. The OLE Regex Match function
    2. The OLE Regex Replace function
    3. The OLE Regex Find (Execute) function
  3. Combining two Regexes
  4. OLE Regex Performance

Regular Expressions can be very useful to the Database programmer, particularly for data validation, data feeds and data transformations. A lot of the time, tools such as grep and awk or Funduc’s S&R will be the most suitable way of using regular expressions, but just occasionally, it is handy to be able to use them in TSQL as we’ll try to show.

Regular Expressions are not regular in the sense that there is any common dialect of expression that is understood by all Regex engines. On the contrary, regular expresssions aren’t always portable and there are many common, similar but incompatible, dialects in use, such as Perl 5.8, Java.util.regex, .NET, PHP, Python, Ruby, ECMA Javascript, PCRE, Apache, vi, Shell tools TCL ARE, POSIX BRE, Funduc and JGsoft.

Regular Expressions were never developed to be easy to understand. They are a condensed shorthand that, on preliminary inspection, looks as if someone has repeatedly sat on the keyboard. Even when interpreted, the logic isn’t always easy to follow.

Probably the best tutorial on the web for Regular Expressions is on www.regular-expressions.info but it is also worth reading Implementing Real-World Data Input Validation using Regular Expressions by Francis Norton for an introduction to regular expressions.

A great deal can be done using commandline applications that work with regular expressions such as GREP and AWK. However, there are times where it is handy to use Regex directly from TSQL. There are two Regex engines available to SQL Server. These are:

  • The .NET Regex which is in the system.text.regularexpression module
  • The ECMA Regex from VBScript.RegExp which is distributed with the IE browser and is used by Javascript and JScript.

Both of these are excellent standard implementations. Both work well in TSQL.

The .NET Regex requires the creation of CLR functions to provide regular expressions, and works only with SQL Server 2005, (and 2007) See CLR Integration by Christoffer Hedgate.

The ECMA Regex can be used via VBScript.RegExp, which are available to SQL Server 2000 as well. The regex is compatible with Javascript.

The advantage of using CLR is that the regular expressions of the NET framework are very good, and performance is excellent. However, the techniques are well-known, whereas some of the more powerful uses of VBScript.RegExp have hardly ever been published, so this workbench will concentrate on the latter

The OLE functions

There are various properties to consider in these functions:

By default, the regular expression is case sensitive. In the following functions, we have set the IgnoreCase property to True to make it case insensitive.
Multiline property
The caret and dollar only match at the very start and very end of the subject string by default. If your subject string consists of multiple lines separated by line breaks, you can make the caret and dollar match at the start and the end of those lines by setting the Multiline property to True. (there is no option to make the dot match line break characters).
Global property
If you want the RegExp object to return or replace all matches instead of just the first one, set the Global property to True.

Only the IgnoreCase is relevant in the first function but we’ve ‘hardcoded’ it to 1 as case-sensitive searches are a minority interest.

The OLE Regex Match function

Let’s start off with something simple, a function for testing a string against a regular expression:

The RegexMatch returns True or False, indicating if the regular expression matches (part of) the string. (It returns null if there is an error). When using this for validating user input, you’ll normally want to check if the entire string matches the regular expression. To do so, put a caret at the start of the regex, and a dollar at the end, to anchor the regex at the start and end of the subject string.

Now, with this routine, we can do some complex input validation.

With this function, the passing back of errors is rudimentary. If an OLE error occurs, then a null is passed back.

There are two other basic Regex functions available. With them, you can use regular expressions in all sorts of places in TSQL without having to get to direct grips with the rather awkward OLE interface.

The OLE Regex Replace function

The RegexReplace function takes three string parameters. The pattern (the regular expression) the replacement expression, and the subject string to do the manipulation to. The replacement expression is one that can cause difficulties. You can specify an empty string '' as the @replacement text. This will cause the Replace method to return the subject string with all regex matches deleted from it (see “strip all HTML elements out of a string” below). To re-insert the regex match as part of the replacement, include $& in the replacement text. (see “find a #comment and add a TSQL –” below). If the regexp contains capturing parentheses, you can use backreferences in the replacement text. $1 in the replacement text inserts the text matched by the first capturing group, $2 the second, etc. up to $9. (e.g. see import delimited text into a database below) To include a literal dollar sign in the replacements, put two consecutive dollar signs in the string you pass to the Replace method.

The OLE Regex Find (Execute) function

This is the most powerful function for doing complex finding and replacing of text. As it passes back detailed records of the hits, including the location and the backreferences, it allows for complex manipulations.

This is written as a table function. The Regex Routine actually passes back a collection for each ‘hit’. In the relational world, you’d normally represent this in two tables, so we’ve returned a left outer join of the two logical tables so as to pass back all the information. This seems to cater for all the uses we can think of. We also append an error column, which should be blank!

Combining two Regexes

Once you’ve experimented with the regex calls we’ve provided, you’ll realise that you can create some really cool functions and procedures that combine regexes. Here we have a procedure that does a ‘google-style’ search on text to find the words you specify. It returns the ‘context’ in that it quotes the substring where the match occurred. You can specify how close the words need to be to specify a ‘hit’.

OLE Regex performance

Whereas the use of the OLE VBScript.RegExp to scan large chunks of text is fine, it is good for complex validation, and it makes a great testbed for regexes, These OLE functions are too slow for use in queries. The overhead of making the calls is just too high because the performance of OLE in TSQL is not great. See Zach Nichter’s excellent article on the subject ‘Writing to a File Using the sp_OACreate Stored Procedure and OSQL’.

Here is an example, scanning a databases of nearly 50,000 names of public houses from out XML Jumpstart Workbench.

It is no consolation for those who are stuck with SQL Server 2000, but the CLR functions are a lot quicker for this sort of usage.

We’ve used a range of regex patterns from a number of sources in this workbench. Like a lot of programmers, we collect up snippets we come across, almost always forgetting to record the original author. We therefore apologise in advance for not crediting the source and original author, of regex patterns. As you can guess, they often take a long time and effort to develop. If you spot a regex which we should have cited, please add a comment and let us all know who originally wrote it!