格式字符串的等价性' [0-9 - +]%'和' [0-9 + - ]%'使用PatIndex

时间:2014-11-14 09:26:42

标签: sql-server tsql

我正在编写一个函数来处理将格式化字符串转换为相对日期,并发现:

Select patindex( '[0-9-+]%', '-Y' ) returns 0

Select patindex( '[0-9+-]%', '-Y' ) returns 1

我认为两个格式字符串是等价的。

0-9-+真的是字符0到9到+?

1 个答案:

答案 0 :(得分:2)

每当方括号中包含一个模式时,在任意两个字符之间输入的任何破折号操作符都意味着匹配排序顺序中所有字符之间的所有字符匹配,这对于大多数标准字符匹配ascii table中的订单。但是,角色不能是两个不同区间的起点和终点:

[0-9]    -- Obviously matches 0 1 2 3 4 5 6 7 8 9
[9-+]    -- Matches nothing, since 9 follows after + in an ascii table.
[+-9]    -- Matches + , - . / 0 1 2 3 4 5 6 7 8 9
[0-9-+]  -- Doesn't work, since two dash operators use the same endpoint twice.
         -- Instead, it seems that the parser interprets this as [09+].
[0-99-+] -- Means the same as [0-9] since + comes before 9 in the ascii table,
         -- so the second interval [9-+] matches nothing.

但是,当短划线操作符位于方括号旁边时,它将包含在匹配项中:

[-]      -- Matches the - character.
[-0-9]   -- Matches the - character, and also 0 1 2 3 4 5 6 7 8 9
[0-9+-]  -- Mathces 0 1 2 3 4 5 6 7 8 9 + -