查找和替换字符串中的数字

时间:2019-04-09 11:43:05

标签: tsql

如果我输入下面给出的字符串,那么我应该能够按照如下所述进行转换。

示例1:字符串-5AB89C应转换为0000000005AB0000000089C

示例2:字符串GH1HJ应该转换为GH0000000001HJ

示例3:字符串N99K7H45应该为B0000000099K0000000007H0000000045

每个数字都应加上10个前导零,包括数字。在示例1中,数字5由9个前导零补全为10位数字,同样的方式89与8个前导零补全为总计10位数字。字母和任何特殊字符都应保持不变。

1 个答案:

答案 0 :(得分:2)

一旦获得PatternSplitCM的副本,这就像馅饼一样容易。

这是我们使用一个值进行操作的方式:

DECLARE @string VARCHAR(8000) = '5AB89C' 

SELECT   CASE f.[matched] WHEN 1 THEN '00000000'+'' ELSE '' END + f.item 
FROM     dbo.patternsplitCM(@String,'[0-9]') AS f
ORDER BY f.ItemNumber
FOR XML PATH('');

返回值: 000000005AB0000000089C

现在针对表格:

-- sample data
DECLARE @table TABLE (StringId INT IDENTITY, String VARCHAR(8000));
INSERT @table(String)
VALUES('5AB89C'),('GH1HJ'),('N99K7H45');

SELECT t.StringId, oldstring = t.String, newstring = f.padded
FROM   @table AS t
CROSS APPLY 
(
  SELECT   CASE f.[matched] WHEN 1 THEN '00000000'+'' ELSE '' END + f.item 
  FROM     dbo.patternsplitCM(t.String,'[0-9]') AS f
  ORDER BY f.ItemNumber
  FOR XML PATH('')
) AS f(padded);

返回:

StringId    oldstring         newstring
----------- ----------------- --------------------------------------
1           5AB89C            000000005AB0000000089C
2           GH1HJ             GH000000001HJ
3           N99K7H45          N0000000099K000000007H0000000045

...就是这样。下面是创建PatternSplitCM的代码。

PatternSplitCM代码:

CREATE FUNCTION dbo.PatternSplitCM
(
       @List                VARCHAR(8000) = NULL
       ,@Pattern            VARCHAR(50)
) RETURNS TABLE WITH SCHEMABINDING 
AS 
RETURN
    WITH numbers AS (
      SELECT TOP(ISNULL(DATALENGTH(@List), 0))
       n = ROW_NUMBER() OVER(ORDER BY (SELECT NULL))
      FROM
      (VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) d (n),
      (VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) e (n),
      (VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) f (n),
      (VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) g (n))
    SELECT
      ItemNumber = ROW_NUMBER() OVER(ORDER BY MIN(n)),
      Item = SUBSTRING(@List,MIN(n),1+MAX(n)-MIN(n)),
      Matched
     FROM (
      SELECT n, y.Matched, Grouper = n - ROW_NUMBER() OVER(ORDER BY y.Matched,n)
      FROM numbers
      CROSS APPLY (
          SELECT Matched = CASE WHEN SUBSTRING(@List,n,1) LIKE @Pattern THEN 1 ELSE 0 END
      ) y
     ) d
     GROUP BY Matched, Grouper