字符串模式替换列

时间:2011-11-14 10:42:15

标签: sql string sql-server-2005 tsql string-matching

因为在SQL中执行正则表达式并不容易,所以我需要一些如何解决这个问题的建议。

我有一个包含以下数据类型的列:

  

Lorem ipsum dolor坐 $%foo ## amet%$ ,奉献精灵。   Nullam odio risus,mollis interdum vitae,rutrum id leo。 Pellentesque   dapibus lobortis mattis。在nisi的一个orci commodo scelerisque的Praesent    $%bar ##%$ eget id dui。 Morbi est arcu,ultricies et consequat ac,   pretium sed mi。 Quisque iaculis pretium congue。 Etiam ullamcorper sapien   在venenatis mauris ultricies的eu mauris tristique。 Proin eu vehicula enim。   Vestibulum aliquam,mauris ac tempus vulputate,odi mauris rhoncus purus,   id suscipit velit erat quis magna。

我需要匹配的粗体文字,需要将其替换为第二部分中的文字。

意义:

  • $%foo##amet%$变为amet
  • $%bar##%$变为空字符串。

作为正则表达式的模式类似于\$%[^#]+?##([^%]*?)%\$

我不能真正使用它,因为在tsql中并不真正支持正则表达式...

有什么建议吗?

3 个答案:

答案 0 :(得分:1)

您拥有的最佳选择是使用具有固定匹配字符串的嵌套REPLACE

SELECT REPLACE(
           REPLACE(YourColumn, '$[%]foo##amet[%]$', 'amet'), '$[%]bar##[%]$', '')

当然,这没有正则表达式的灵活性....

或者你可以设计一个SQL-CLR正则表达式库(或find one of the pre-existing ones)并将它们包含在你的SQL Server中 - 从2005年开始,SQL Server 可以执行.NET代码,以及某些东西像正则表达式库是扩展具有.NET功能的T-SQL的完美示例。

答案 1 :(得分:0)

您必须执行以下代码:

SELECT REPLACE(REPLACE(YourColumn, ' $%amet%$ ', ' amet '), ' $%bar%$ ', ' ')

%字符表示“任何字符串零个或多个字符”,如here所述。 您需要放置空格以仅识别单个单词:)

答案 2 :(得分:0)

用这个函数修复它:

CREATE FUNCTION [dbo].[ReplaceWithDefault]
(
   @InputString VARCHAR(4000)
)
RETURNS VARCHAR(4000)
AS
BEGIN
    DECLARE @Pattern VARCHAR(100) SET @Pattern = '$[%]_%##%[%]$'
    -- working copy of the string
    DECLARE @Result VARCHAR(4000) SET @Result = @InputString
    -- current match of the pattern
    DECLARE @CurMatch VARCHAR(500) SET @curMatch = ''
    -- string to replace the current match
    DECLARE @Replace VARCHAR(500) SET @Replace = ''
    -- start + end of the current match
    DECLARE @Start INT
    DECLARE @End INT
    -- length of current match
    DECLARE @CurLen INT
    -- Length of the total string -- 8001 if @InputString is NULL
    DECLARE @Len INT SET @Len = COALESCE(LEN(@InputString), 8001)

    WHILE (PATINDEX('%' + @Pattern + '%', @Result) != 0) 
    BEGIN
        SET @Replace = ''

        SET @Start = PATINDEX('%' + @Pattern + '%', @Result)
        SET @CurMatch = SUBSTRING(@Result, @Start, @Len)

        SET @End = PATINDEX('%[%]$%', @CurMatch) + 2
        SET @CurMatch = SUBSTRING(@CurMatch, 0, @End)

        SET @CurLen = LEN(@CurMatch)

        SET @Replace = REPLACE(RIGHT(@CurMatch, @CurLen - (PATINDEX('%##%', @CurMatch)+1)), '%$', '')

        SET @Result = REPLACE(@Result, @CurMatch, @Replace)
    END
    RETURN(@Result)
END