SQL Server Regular Expression Replacement Function

-- delete the original function if it exists
IF OBJECT_ID(N'dbo.RegexReplace') IS NOT NULL
    DROP FUNCTION dbo.RegexReplace
GO
--Start creating a regular replacement function
 CREATE FUNCTION dbo.RegexReplace
(
	@string VARCHAR(MAX), -- the string to be replaced
	@pattern VARCHAR(255), -- replace template
	@replacestr VARCHAR(255), --replaced string
	@IgnoreCase INT=0 --0 case sensitive 1 case insensitive
)
RETURNS VARCHAR(8000)
AS
BEGIN
    DECLARE @objRegex INT, @retstr VARCHAR (8000)
	--create object
	EXEC sp_OACreate 'VBScript.RegExp', @objRegex OUT
	--set properties
	EXEC sp_OASetProperty @objRegex, 'Pattern', @pattern
	EXEC sp_OASetProperty @objRegex, 'IgnoreCase', @IgnoreCase
	EXEC sp_OASetProperty @objRegex, 'Global', 1
	--implement
	EXEC sp_OAMethod @objRegex, 'Replace', @retstr OUT, @string, @replacestr
	--freed
	EXECUTE sp_OADestroy @objRegex
	RETURN @retstr
END
GO
--To ensure normal operation, you need to set the Ole Automation Procedures option to 1 ?
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE WITH OVERRIDE;
EXEC sp_configure 'Ole Automation Procedures', 1;
RECONFIGURE WITH OVERRIDE;

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326698266&siteId=291194637