【发布时间】:2015-09-27 20:59:24
【问题描述】:
我写了一个短语,它将一个很长的字符串分成小段,在完成一个项目的短语后,它将他从@input中删除并继续,直到它无法找到任何要短语的项目。 我正在根据 LIKE 模式选择项目。
在某些情况下,它会选择消息的其他部分,然后以不定式循环结束。
我希望使用 LIKE 子句选择的模式格式为:
(从 1 到 9 的任何数字)+(仅可变长度 A-Z)+ '/' + (仅可变长度 A-Z)+Cr 或 Lf 或 CrLf 的空格。
--This is what I do have:
DECLARE @match NVarChar(100)
SET @match = '%[1-9][a-z]%'
DECLARE @input1 varchar(max),@input2 varchar(max)
SET @input1 ='1ABCD/EFGH *W/17001588 *RHELLO SMVML1C'
DECLARE @position Int
SET @position = PATINDEX(@match, @input1);
SELECT @position;
--after the loop- it is also 'catching' the 1C at the end of the string:
SET @input2 = '*W/17001588 *RHELLO SMVML1C'
SET @position = PATINDEX(@match, @input2);
SELECT @position
---In order to eliminate this, I have tried to change @match:
SET @match = '%[1-9][a-z][/][a-z]%'
SET @position = PATINDEX(@match, @input1);
SELECT @position --postion is 0, so the first item, that should have been selected, wasn't selected
SET @position = PATINDEX(@match, @input2);
SELECT @position --postion is 0
非常感谢您的帮助!
【问题讨论】:
-
T-SQL 没有正则表达式或任何其他内置模式匹配器可以满足您的需求。特别是“任意数量”和“可变长度”部分会导致问题。
-
那么在你的新比赛中,
@input1,@position应该是 1,@input2,@position应该是 0?对吗? -
您无法使用 PATINDEX 的有限功能解析此类输入。您应该在代码中使用正则表达式或编写一个实际的解析器。
-
您是否考虑过使用其他工具?
-
使用 CLR 和正则表达式
[\d][A-Z]+/[A-Z]+[ \r\n]这很简单。
标签: sql-server tsql sql-server-2012 sql-like