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 Replace

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

CREATE FUNCTION dbo.RegexReplace (
	@pattern VARCHAR(255)
	,@replacement VARCHAR(255)
	,@Subject VARCHAR(MAX)
	,@global BIT = 1
	,@Multiline BIT = 1
	)
RETURNS VARCHAR(MAX)
	/*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.*/
AS
BEGIN
	DECLARE @objRegexExp INT
		,@objErrorObject INT
		,@strErrorMessage VARCHAR(255)
		,@Substituted VARCHAR(8000)
		,@hr INT
		,@Replace BIT

	SELECT @strErrorMessage = 'creating a regex object'

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

	IF @hr = 0
		SELECT @strErrorMessage = 'Setting the Regex pattern'
			,@objErrorObject = @objRegexExp

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

	IF @hr = 0 /*By default, the regular expression is case sensitive. Set the IgnoreCase property to True to make it case insensitive.*/
		SELECT @strErrorMessage = 'Specifying the type of match'

	IF @hr = 0
		EXEC @hr = sp_OASetProperty @objRegexExp
			,'IgnoreCase'
			,1

	IF @hr = 0
		EXEC @hr = sp_OASetProperty @objRegexExp
			,'MultiLine'
			,@Multiline

	IF @hr = 0
		EXEC @hr = sp_OASetProperty @objRegexExp
			,'Global'
			,@global

	IF @hr = 0
		SELECT @strErrorMessage = 'Doing a Replacement'

	IF @hr = 0
		EXEC @hr = sp_OAMethod @objRegexExp
			,'Replace'
			,@Substituted OUT
			,@subject
			,@Replacement

	/*If the RegExp.Global property is False (the default), Replace will return the @subject string with the first regex match (if any) substituted with the replacement text. If RegExp.Global is true, the @Subject string will be returned with all matches replaced.*/
	IF @hr <> 0
	BEGIN
		DECLARE @Source VARCHAR(255)
			,@Description VARCHAR(255)
			,@Helpfile VARCHAR(255)
			,@HelpID INT

		EXECUTE sp_OAGetErrorInfo @objErrorObject
			,@source OUTPUT
			,@Description OUTPUT
			,@Helpfile OUTPUT
			,@HelpID OUTPUT

		SELECT @strErrorMessage = 'Error whilst ' + COALESCE(@strErrorMessage, 'doing something') + ', ' + COALESCE(@Description, '')

		RETURN @strErrorMessage
	END

	EXEC sp_OADestroy @objRegexExp

	RETURN @Substituted
END
GO
--remove repeated words in text
SELECT  dbo.RegexReplace('b(w+)(?:s+1b)+', '$1',
                         'Sometimes I cant help help help stuttering',1, 1)

--find a #comment and add a TSQL --
SELECT  dbo.RegexReplace('#.*','--$&','
# this is a comment
first,second,third,fourth',1,1)

--replace a url with an HTML anchor
SELECT  dbo.RegexReplace(
        'b(https?|ftp|file)://([-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|])',
        '<a href="$2">$2</a>',
         'There is  this amazing site at http://www.simple-talk.com',1,1)

--strip all HTML elements out of a string
SELECT  dbo.RegexReplace('<(?:[^>''"]*|([''"]).*?1)*>',
   '','<a href="http://www.simple-talk.com">Simle Talk is wonderful</a><!--This is a comment --> we all love it',1,1)

--import delimited text into a database, converting it into insert statements
SELECT  dbo.RegexReplace(
 '([^|rn]+)[|rn]+([^|rn]+)[|rn]+([^|rn]+)[|rn]+([^|rn]+)[|rn]+',
 'Insert into MyTable (Firstcol,SecondCol, ThirdCol, Fourthcol)
select $1,$2,$3,$4
','1|white gloves|2435|24565
2|Sports Shoes|285678|0987
3|Stumps|2845|987
4|bat|29862|4875',1,1)
/*

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

PowerShell – Battery Charge Status

Posted on November 9, 2015

Add-Type -AssemblyName System.Windows.Forms [Windows.Forms.PowerStatus].GetConstructor( [Reflection.BindingFlags]36, $null, [Type[]]@(), $null ).Invoke($null) Reference: http://poshcode.org/5687 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…

Read More

PowerShell – Get Computer Information

Posted on November 6, 2015November 10, 2015

This script is pieced together from various posts, I only take credit for combining the resources. There is more than initially is seen to this script, based on the code below it will write a text file on c:\ and does need admin privileges in order to run. Right around…

Read More

Web Browser Controls

Posted on April 11, 2013March 3, 2016

C# Visual Studio 2010 Project C# WebBrowser using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace WebBrowser { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnNavigate_Click(object sender, EventArgs e) { webBrowser1.Navigate(txtAddressBar.Text); } private void btnBack_Click(object sender, EventArgs…

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
 

Loading Comments...
 

You must be logged in to post a comment.