2017-06-20 47 views
0

我正在寻找RegExp来查找SQL Server和正则表达式(RegExp)中整个单词中的重复字符。例如:用于查找连续重复字符的T-SQL RegExp

"AAUGUST"  match (AA) 

"ANDREA"  don't match (are 2 vowels "A", buit are separated) 

"ELEEPHANT" match (EE) 

我与努力:

SELECT field1 
FROM exampleTable 
WHERE field1 like '%([A-Z]){2}%' 

但它不工作。

我喜欢你的帮助。

谢谢!

+0

尽管即使MS误导性地暗示,否则“LIKE”不支持正则表达式。它支持的模式比简单的字符串搜索更强大,但是比正则表达式强大得多。这就是说,虽然'LIKE'在这里不太可能有用,否则很可能会有一种完全不同的方式来实现你所追求的。 – hvd

回答

0

你不能用T-SQL的LIKE做什么。

最好的办法是看使用Common Language Runtime (CLR),但它也可以使用实现(虽然痛苦慢),例如,一个标值函数如下:

create function dbo.ContainsRepeatingAlphaChars(@str nvarchar(max)) returns bit 
as begin 
    declare @p int, -- the position we're looking at 
      @c char(1) -- the previous char 

    if @str is null or len(@str) < 2 return 0; 

    select @c = substring(@str, 1, 1), @p = 1; 

    while (1=1) begin 
     set @p = @p + 1;     -- move position pointer ahead 
     if @p > len(@str) return 0;  -- if we're at the end of the string and haven't already exited, we haven't found a match 
     if @c like '[A-Z]' and @c = substring(@str, @p, 1) return 1; -- if last char is A-Z and matches the current char then return "found!" 
     set @c = substring(@str, @p, 1); -- Get next char 
    end 
    return 0; -- this will never be hit but stops SQL Server complaining that not all paths return a value 
end 
GO 

-- Example usage: 
SELECT field1 
FROM exampleTable 
WHERE dbo.ContainsRepeatingAlphaChars(field1) = 1 

我提到它会很慢?不要在大桌子上使用它。去CLR。

+0

我认为你是对的。也许最好的办法是用“像”与所有的选项: LIKE“%AA%”或 LIKE“%BB%”或 ... 等 – user3623482

+0

这将是缓慢的,以及,其实我想打赌它会比我上面的函数慢,但如果CLR真的不是一个选项,那么值得运行一些测试来看看你将使用这两种方法与你的数据集进行什么类型的性能比较 – pcdev