找到输入字符串中模式的所有索引

时间:2014-04-16 10:37:26

标签: string tsql

我需要在输入法中找到' '(空格)和'-'(短划线)的所有索引 试图使用patindex,但有几个问题:

  1. 它只找到模式的第一个实例
  2. 如何构建模式?如果我设置' - '它寻找序列和我的魔杖或' - '或者' '

1 个答案:

答案 0 :(得分:1)

参考my answer on PatternReplace,您可以简单地调整功能:

CREATE FUNCTION "dbo"."GetIndices"
(
   @InputString VARCHAR(4000),
   @Pattern VARCHAR(100)
)
RETURNS @indices table
(
    pos int
)
AS
BEGIN
   DECLARE @count INT
   DECLARE @Result VARCHAR(4000) SET @Result = ''
   -- First character in a match
   DECLARE @First INT
   -- Next character to start search on
   DECLARE @Next INT SET @Next = 1
   -- Length of the total string -- 8001 if @InputString is NULL
   DECLARE @Len INT SET @Len = COALESCE(LEN(@InputString), 8001)
   -- End of a pattern
   DECLARE @EndPattern INT

   WHILE (@Next <= @Len) 
   BEGIN
      SET @First = PATINDEX('%' + @Pattern + '%', SUBSTRING(@InputString, @Next, @Len))
      --insert into @indices( pos ) values ( @first )

      IF COALESCE(@First, 0) = 0 --no match - return
      BEGIN
         SET @Result = @Result + 
            CASE --return NULL, just like REPLACE, if inputs are NULL
               WHEN  @InputString IS NULL
                     OR @Pattern IS NULL THEN NULL
               ELSE SUBSTRING(@InputString, @Next, @Len)
            END
         BREAK
      END
      ELSE
      BEGIN
         -- Concatenate characters before the match to the result
         SET @Result = @Result + SUBSTRING(@InputString, @Next, @First - 1)
         SET @Next = @Next + @First - 1
         insert into @indices( pos ) values ( @next )
         SET @EndPattern = 1
         -- Find start of end pattern range
         WHILE PATINDEX(@Pattern, SUBSTRING(@InputString, @Next, @EndPattern)) = 0
            SET @EndPattern = @EndPattern + 1
         -- Find end of pattern range
         WHILE PATINDEX(@Pattern, SUBSTRING(@InputString, @Next, @EndPattern)) > 0
               AND @Len >= (@Next + @EndPattern - 1)
            SET @EndPattern = @EndPattern + 1

         --Either at the end of the pattern or @Next + @EndPattern = @Len
         SET @Next = @Next + @EndPattern - 1
      END
   END
   RETURN
END

并像

一样使用它
SELECT * FROM "dbo"."GetIndices"( '1 1 1-1-1', '[- ]' )

请参阅此SQL-Fiddle了解演示。

结果:

POS
2
4
6
8