34,837
社区成员




CREATE function dbo.regexReplace
(
@source varchar(5000), --原字符串
@regexp varchar(1000), --正则表达式
@replace varchar(1000), --替换值
@globalReplace bit = 0, --是否是全局替换
@ignoreCase bit = 0 --是否忽略大小写
)
returnS varchar(1000) AS
begin
declare @hr integer
declare @objRegExp integer
declare @result varchar(5000)
exec @hr = sp_OACreate 'VBScript.RegExp', @objRegExp OUTPUT
IF @hr <> 0 begin
exec @hr = sp_OADestroy @objRegExp
return null
end
exec @hr = sp_OASetProperty @objRegExp, 'Pattern', @regexp
IF @hr <> 0 begin
exec @hr = sp_OADestroy @objRegExp
return null
end
exec @hr = sp_OASetProperty @objRegExp, 'Global', @globalReplace
IF @hr <> 0 begin
exec @hr = sp_OADestroy @objRegExp
return null
end
exec @hr = sp_OASetProperty @objRegExp, 'IgnoreCase', @ignoreCase
IF @hr <> 0 begin
exec @hr = sp_OADestroy @objRegExp
return null
end
exec @hr = sp_OAMethod @objRegExp, 'Replace', @result OUTPUT, @source, @replace
IF @hr <> 0 begin
exec @hr = sp_OADestroy @objRegExp
return null
end
exec @hr = sp_OADestroy @objRegExp
IF @hr <> 0 begin
return null
end
return @result
end
--创建临时表:
create table a
(
context nvarchar(1000)
);
--插入测试数据:
insert into a values('<html>
<head>
<script type="text/javascript">
function getValue()
{
var x=document.getElementById("myHeader")
alert(x.innerHTML)
}
</script>
</head>
<body>
<h1 id="myHeader" onclick="getValue()">这是标题</h1>
<p>点击标题,会提示出它的值。</p>
</body>
< ml>');
select dbo.regexReplace(context,'(?:(?:<(?:STYLE|style|SCRIPT|script)[^>]*>[\s\S]+?</(?:STYLE|style|SCRIPT|script)>)|(?:<[^>]+>)|(?:[\s{2,}\n]+))','',1,1) from a;
/*
------
这是标题点击标题,会提示出它的值。
*/
chr(34)对应"
replace(col,char(34),'')
SELECT replace('"2222222','"','' )RES
SELECT replace('"2222222','"','' )RES
SELECT replace('"2222222',N'"','' )RES
SELECT replace(N'"2222222','"','' )RES
SELECT replace(N'"2222222',N'"','' )RES
RES
----------------------
2222222
(1 row(s) affected)
create table tb(col varchar(20))
insert into tb values('"')
insert into tb values('1"')
insert into tb values('2"')
insert into tb values('34"')
select replace(col,'"',' ' ) from tb
drop table tb
/*
------
1
2
34
(所影响的行数为 4 行)
*/
create table tb(col varchar(20))
insert into tb values('"')
insert into tb values('1"')
insert into tb values('2"')
insert into tb values('34"')
select replace(col,N'"',' ' ) from tb
drop table tb
/*
------
1
2
34
(所影响的行数为 4 行)
*/