将多个特殊字符替换为单个破折号

时间:2018-05-22 10:57:03

标签: sql-server sql-server-2014

您好我的数据为(SCARF。)/(WRAPS),我想将其显示为SCARF-WRAPS,但我无法得到它

我的下面的代码是

DECLARE @str VARCHAR(400)
DECLARE @specialchars VARCHAR(50) = '%[/,~,@,#,$,%,&,*,(,),.,!^?:]%'
--SET @str = 'KRA!NTHI@#KUMAR, KU%^?MAR GO~()$U.BigGrin'
SET @str = '(SCARF.) / (WRAPS)'
SET @str = REPLACE(@str,'.','')
WHILE PATINDEX( @specialchars, @str ) > 0
SET @str = REPLACE(REPLACE( @str, SUBSTRING( @str, PATINDEX( @specialchars, @str ), 1 ),'-'),'-','-')

IF(LEFT(@str, 1) = '-')
   set @str = RIGHT(@str, LEN(@str) - 1)
IF(RIGHT(@str, 1) = '-')
   set @str = LEFT(@str, LEN(@str) - 1)

SELECT REPLACE(@str,' ','-')

但它提供数据为SCARF ----- WRAPS而不是SCARF-WRAPS

我有这样的数据类型为多个,我想将它们转换为单个破折号。

例如:

  

'皮肤护理&美容供应'应改为“皮肤护理 - 美容 - 供应”

     

' BANDANAS / DURAGS / WRAPS'应改为' BANDANAS-DURAGS-WRAPS'

     

' HATS&消声器'应该改为“HATS-MUFFLERS'

2 个答案:

答案 0 :(得分:0)

我不会说这个解决方案很漂亮;不是。它完成了这项工作,但我不希望它能够快速运作。它使用了Alan Burstein的NGrams8k,所以你需要确保你的服务器上也有副本。

如果您不理解,请随意询问(除了NGrams8K如何工作,这就是文章的用途):

CREATE TABLE T (string varchar(400));
INSERT INTO T
VALUES ('KRA!NTHI@#KUMAR, KU%^?MAR GO~()$U.BigGrin'),
       ('(SCARF.) / (WRAPS)');
GO
WITH Replacements AS (
    SELECT *,
           CASE WHEN NG.token NOT LIKE '[ /,~@#$%&*().!^?:]' THEN NG.token ELSE '-' END AS TokenR
    FROM T
         CROSS APPLY dbo.NGrams8k ('-'+T.String+'-',1) NG),
Repeating AS (
    SELECT *,
           CASE WHEN TokenR = '-' AND TokenR = LAG(TokenR) OVER (PARTITION BY string ORDER BY position) THEN NULL ELSE TokenR END AS TokenRR
    FROM Replacements),
Cleaned AS (
    SELECT string,
           STUFF((SELECT sq.TokenRR + ''
                  FROM Repeating sq
                  WHERE sq.TokenRR IS NOT NULL
                    AND sq.string = R.string
                  ORDER BY position
                  FOR XML PATH('')),1,1,'') AS CleanString
    FROM Repeating R
    GROUP BY string)
SELECT string, LEFT(CleanString, LEN(CleanString)-1) AS CleanedString
FROM Cleaned;

GO
DROP TABLE T;

提供样本数据后,您将获得以下输出:

string                                     | CleanedString
-------------------------------------------|---------------------------------
(SCARF.) / (WRAPS)                         | SCARF-WRAPS
KRA!NTHI@#KUMAR, KU%^?MAR GO~()$U.BigGrin  | KRA-NTHI-KUMAR-KU-MAR-GO-U-BigGrin

答案 1 :(得分:0)

试试这个:

DECLARE @str VARCHAR(400)='(SCARF.) / (WRAPS)'
DECLARE @specialchars VARCHAR(50) = '%[/,~,@,#,$,%,&,*,(,),.,!^?:-]%'

WHILE PATINDEX( @specialchars, @str ) > 0
SET @str = REPLACE( @str, SUBSTRING( @str, PATINDEX( @specialchars, @str ), 1 ),' ')

SELECT REPLACE(REPLACE(REPLACE(RTRIM(LTRIM(@str)), ' ', '- '), ' -', ''), ' ', '')