TSQL如何在字符串中查找模式?

时间:2012-06-28 22:50:32

标签: tsql

我有一个字符串:

'This is some random text so you don't get upset [rethink]'

或此字符串

'This is some random text so you don't get upset [me] and [123]'

是否可以使用TSQL查找和替换[text]字符串?

结果:

'This is some random text so you don't get upset '

或此字符串

'This is some random text so you don't get upset  and '

修改

我修改了接受的答案,使功能更加动态:

CREATE FUNCTION [dbo].[StripTagWithChar]
(@TagLeft NVARCHAR(1),@TagText NVARCHAR(MAX),@TagRight NVARCHAR(1))
RETURNS NVARCHAR(MAX)
AS
BEGIN
    DECLARE @Start INT
    DECLARE @End INT
    DECLARE @Length INT
    SET @Start = CHARINDEX(@TagLeft,@TagText)
    SET @End = CHARINDEX(@TagRight,@TagText,@Start+1)
    SET @Length = (@End - @Start) + 1

    WHILE (@Start > 0
        AND @End > 0
        AND @Length > 0)
    BEGIN
        SET @TagText = STUFF(@TagText,@Start,@Length,'')
        SET @Start = CHARINDEX(@TagLeft,@TagText)
        SET @End = CHARINDEX(@TagRight,@TagText,@Start+1)
        SET @Length = (@End - @Start) + 1
    END

    RETURN Replace(LTRIM(RTRIM(@TagText)),'  ',' ')
END

现在这个函数接受括号括号作为输入:

select [dbo].[StripTagWithChar]( '{' , 'this is {not} awesome' , '}' )

最酷的是,现在它将使用相同的括号过滤标签:

select [dbo].[StripTagWithChar]( '=' , 'this is =not= awesome' , '=' )

1 个答案:

答案 0 :(得分:3)

我建议对a previously created UDF that strips out HTML tags做一些修改......只需将<>替换为[]

CREATE FUNCTION [dbo].[udf_StripTag]
(@TagText VARCHAR(MAX))
RETURNS VARCHAR(MAX)
AS
BEGIN
    DECLARE @Start INT
    DECLARE @End INT
    DECLARE @Length INT
    SET @Start = CHARINDEX('[',@TagText)
    SET @End = CHARINDEX(']',@TagText,CHARINDEX('[',@TagText))
    SET @Length = (@End - @Start) + 1

    WHILE (@Start > 0
        AND @End > 0
        AND @Length > 0)
    BEGIN
        SET @TagText = STUFF(@TagText,@Start,@Length,'')
        SET @Start = CHARINDEX('[',@TagText)
        SET @End = CHARINDEX(']',@TagText,CHARINDEX('[',@TagText))
        SET @Length = (@End - @Start) + 1
    END

    RETURN LTRIM(RTRIM(@TagText))
END
GO