34,588
社区成员
发帖
与我相关
我的任务
分享
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 sqlclr
go
use sqlclr
go
exec sp_configure 'clr enabled', '1'
go
reconfigure;
exec sp_configure 'show advanced options', '1';
go
ALTER DATABASE sqlclr SET TRUSTWORTHY On
go
CREATE ASSEMBLY SqlClr_RegEx FROM 'E:\sqlclrdata\SQLCLR_RegExp.dll' WITH PERMISSION_SET = UnSAFE;
--
go
CREATE FUNCTION dbo.ufn_RegExp_Like
(
@input nvarchar(max),
@pattern nvarchar(4000)
)
RETURNS bit
AS EXTERNAL NAME SqlClr_RegEx.RegExp.RegExp_Like
go
CREATE 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 on
declare @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 @t
where 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.com
fdf**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;
}
}