Skip to content
David Kittell
David Kittell

Application & System: Development / Integration / Orchestration

  • Services
    • Application Development
    • Online Application Integration
  • Code
  • Online Tools
  • Tech Support
David Kittell

Application & System: Development / Integration / Orchestration

Regex Match

Posted on August 6, 2013October 26, 2015 By David Kittell
IF OBJECT_ID(N'dbo.RegexMatch') IS NOT NULL
	DROP FUNCTION dbo.RegexMatch
GO

CREATE FUNCTION dbo.RegexMatch (
	@pattern VARCHAR(2000)
	,@matchstring VARCHAR(MAX) --Varchar(8000) got SQL Server 2000
	)
RETURNS INT
	/* 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.
*/
AS
BEGIN
	DECLARE @objRegexExp INT
		,@objErrorObject INT
		,@strErrorMessage VARCHAR(255)
		,@hr INT
		,@match BIT

	SELECT @strErrorMessage = 'creating a regex object'

	EXEC @hr = sp_OACreate 'VBScript.RegExp'
		,@objRegexExp OUT

	IF @hr = 0
		EXEC @hr = sp_OASetProperty @objRegexExp
			,'Pattern'
			,@pattern

	--Specifying a case-insensitive match
	IF @hr = 0
		EXEC @hr = sp_OASetProperty @objRegexExp
			,'IgnoreCase'
			,1

	--Doing a Test'
	IF @hr = 0
		EXEC @hr = sp_OAMethod @objRegexExp
			,'Test'
			,@match OUT
			,@matchstring

	IF @hr <> 0
	BEGIN
		RETURN NULL
	END

	EXEC sp_OADestroy @objRegexExp

	RETURN @match
END
GO
--IS there a repeating word
SELECT dbo.RegexMatch('b(w+)s+1b','this has has been repeated')--1
SELECT dbo.RegexMatch('b(w+)s+1b','this has not been repeated')--0

--find a word near another word (in this case 'for' and 'last' 1 or 2 words apart)
SELECT dbo.RegexMatch('bfor(?:W+w+){1,2}?W+lastb',
           'You have failed me for the last time, Admiral')--1
SELECT dbo.RegexMatch('bfor(?:W+w+){1,2}?W+lastb',
           'You have failed me for what could be the last time, Admiral')--0

--is this likely to be a valid credit card
SELECT dbo.RegexMatch('^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|3(?:0
[0-5]|[68][0-9])[0-9]{11}|3[47][0-9]{13}|(?:2131|1800)d{11})$','4953129482924435')

--IS this a valid ZIP code
SELECT dbo.RegexMatch('^[0-9]{5,5}([- ]?[0-9]{4,4})?$','02115-4653')

--is this a valid Postcode
SELECT dbo.RegexMatch('^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha
-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))
) {0,1}[0-9][A-Za-z]{2})$','RG35 2AQ')

--is this a valid European date
SELECT dbo.RegexMatch('^((((31/(0?[13578]|1[02]))|((29|30)/(0?[1,3-9]|1[0-2])))/(1[
6-9]|[2-9]d)?d{2})|(29/0?2/(((1[6-9]|[2-9]d)?(0[48]|[2468][048]|[13579][26])|((16
|[2468][048]|[3579][26])00))))|(0?[1-9]|1d|2[0-8])/((0?[1-9])|(1[0-2]))/((1[6-9]|[2
-9]d)?d{2})) (20|21|22|23|[0-1]?d):[0-5]?d:[0-5]?d$','12/12/2007 20:15:27')

--is this a valid currency value (dollar)
SELECT dbo.RegexMatch('^$(d{1,3}(,d{3})*|(d+))(.d{2})?$','$34,000.00')

--is this a valid currency value (Sterling)
SELECT dbo.RegexMatch('^&pound;(d{1,3}(,d{3})*|(d+))(.d{2})?$',
'&pound;34,000.00')

--A valid email address?
SELECT dbo.RegexMatch('^(([a-zA-Z0-9!#$%^&*{}''`+=-_|/?]+(.[a-zA-Z0-9!#$%^&
*{}''`+=-_|/?]+)*){1,64}@(([A-Za-z0-9]+[A-Za-z0-9-_]*){1,63}.)*(([A-Za-z0-9]+[A
-Za-z0-9-_]*){3,63}.)+([A-Za-z0-9]{2,4}.?)+){1,255}$','Phil.Factor@simple-Talk.com')

Source: https://www.simple-talk.com/sql/t-sql-programming/tsql-regular-expression-workbench/

Originally Posted on August 6, 2013
Last Updated on October 26, 2015
All information on this site is shared with the intention to help. Before any source code or program is ran on a production (non-development) system it is suggested you test it and fully understand what it is doing not just what it appears it is doing. I accept no responsibility for any damage you may do with this code.

Related

Code MSSQL

Post navigation

Previous post
Next post

Related Posts

Mac OSX Terminal – Create New Admin User

Posted on December 8, 2017

#!/bin/sh # CreateAdminUser.sh # # Created by David Kittell on 12/8/17. # clear userFullName=$1 userName=$2 userPassword=$3 echo "Checking If User Exists" # List Local Users # dscl . list /Users | grep -v ‘_’ if [[ $(dscl . list /Users) =~ "$userName" ]]; then echo "User Exists" else echo "User…

Read More

Eject CD/DVD

Posted on December 14, 2013October 26, 2015

Public Sub ejectCDRom() Dim i As Integer ‘code to eject cdrom ok Dim owmp As Object Dim colCDROMs As Object owmp = CreateObject("WMPlayer.OCX.7") colCDROMs = owmp.cdromCollection If colCDROMs.Count >= 1 Then For i = 0 To colCDROMs.Count – 1 colCDROMs.Item(i).eject() Next End If End Sub Public Class Form1 Private Declare…

Read More

MSSQL – Table/View Column Information

Posted on February 25, 2013October 26, 2015

Similar to MySQL – Table/View Column Information, this post will help with MSSQL tables and columns. exec sp_columns ‘<tablename>’ Cleaner Result: SET NOCOUNT ON DECLARE @tablename NVARCHAR(max) SET @tablename = <tablename> SELECT c.NAME ‘Column Name’ ,t.NAME ‘Data type’ ,c.max_length ‘Max Length’ , –c.precision , –c.scale , CASE c.is_nullable WHEN 0…

Read More

Code

Top Posts & Pages

  • PowerShell - Rename Pictures to Image Taken
  • Front Page
  • C# - Start/Stop/Restart Services
  • MacPorts / HomeBrew - Rip CD tracks from terminal
  • PowerShell - Show File Extensions

Recent Posts

  • Javascript – Digital Clock with Style
  • BASH – Web Ping Log
  • BASH – Picture / Video File Name Manipulation
  • Mac OSX Terminal – Create SSH Key
  • Bash – Rename Picture

Top Posts

  • PowerShell - Rename Pictures to Image Taken
  • C# - Start/Stop/Restart Services
  • MacPorts / HomeBrew - Rip CD tracks from terminal
  • PowerShell - Show File Extensions
  • Open On Screen Keyboard (OSK)
  • SQLite - Auto-Increment / Auto Generate GUID
©2025 David Kittell | WordPress Theme by SuperbThemes