【交流】SQL2005CLR函数扩展-正则表达式
blog地址,欢迎大家访问我的博客。
http://blog.csdn.net/jinjazz/archive/2009/04/22/4101746.aspx
用过Oracle的人都知道Oracle有四个正则表达函数REGEXP_LIKE、REGEXP_INSTR、REGEXP_SUBSTR、和 EGEXP_REPLACE,而SQLServer却无法完全实现上面的功能。以前我们知道用sp_OAxxx系列函数来调用js组建实现正则,现在我们可以通过CLR扩展来借助.Net实现。
※代码很简单,就是封装一下System.Text.RegularExpressions.Regex到SQLProject当中。我们可以用下面15行代码完成上述的四个函数中的最常用的两个REGEXP_LIKE和EGEXP_REPLACE。
using System;using System.Data.SqlTypes;public partial class RegExp{ [Microsoft.SqlServer.Server.SqlFunction] public static SqlBoolean RegExp_Like(SqlString input,SqlString pattern) { if (input.IsNull || pattern.IsNull) return false; return System.Text.RegularExpressions.Regex.IsMatch(input.Value, pattern.Value); } [Microsoft.SqlServer.Server.SqlFunction] public static SqlString RegExp_Replace(SqlString input,SqlString pattern,SqlString replacement) { if (input.IsNull || pattern.IsNull || replacement.IsNull) return input; return new System.Text.RegularExpressions.Regex(pattern.Value).Replace(input.Value, replacement.Value); }};create database sqlclrgouse sqlclr goexec sp_configure 'clr enabled', '1'goreconfigure;exec sp_configure 'show advanced options', '1';go ALTER DATABASE sqlclr SET TRUSTWORTHY On goCREATE ASSEMBLY SqlClr_RegEx FROM 'E:\sqlclrdata\SQLCLR_RegExp.dll' WITH PERMISSION_SET = UnSAFE;--goCREATE FUNCTION dbo.ufn_RegExp_Like ( @input nvarchar(max), @pattern nvarchar(4000)) RETURNS bitAS EXTERNAL NAME SqlClr_RegEx.RegExp.RegExp_LikegoCREATE FUNCTION dbo.ufn_RegExp_Replace ( @input nvarchar(max), @pattern nvarchar(4000), @replacement nvarchar(4000)) RETURNS nvarchar(max)AS EXTERNAL NAME SqlClr_RegEx.RegExp.RegExp_Replace
set nocount ondeclare @t table(teststring varchar(50))insert into @t select '上海市南京路100号2弄3号'insert into @t select 'jinjazz@sina.com.cn'insert into @t select '剪刀@msn.com'insert into @t select 'fdf98s'--获取合法邮箱select * from @twhere dbo.ufn_RegExp_Like(teststring,'\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*')>0/*teststring--------------------------------------------------jinjazz@sina.com.cn剪刀@msn.com*/--替换数字select dbo.ufn_RegExp_Replace(teststring,'[\d*$]','*') as newstring from @t/*newstring-------------------------------------------------上海市南京路***号*弄*号jinjazz@sina.com.cn剪刀@msn.comfdf**s*/set nocount off
[Microsoft.SqlServer.Server.SqlFunction] public static SqlBoolean RegExp_Like(SqlString input,SqlString pattern) { try { if (string.IsNullOrEmpty(input) || string.IsNullOrEmpty(pattern)) return false; Regex reg = new Regex(pattern, RegexOptions.Compiled); return reg.IsMatch(input); } catch (ArgumentException ex) { return false; } catch (Exception ex) { return false; } }