2012-11-30 44 views
1

我有一個C#中的SQL Server CLR,其功能類似於SQL Server CHARINDEX函數,但允許使用正則表達式。SQL Server RegExIndex CLR返回錯誤的索引位置

[SqlFunction] 
public static SqlInt32 RegExIndex(SqlChars input, SqlString pattern, SqlInt32 beginning) 
{ 
    Regex regex = new Regex(pattern.Value, Options); 
    Match match = regex.Match(new string(input.Value), beginning.Value); 
    return match.Index; 
} 

在測試中,我發現了以下收益3時,它應該返回1:

select dbo.RegExIndex('test', 't', 1) 

下返回0,當它應該返回4:

select dbo.RegExIndex('test', 't', 4) 

我想,也許開始參數是零基地,但是當它應該返回1時它也返回0:

select dbo.RegExIndex('test', 't', 0) 

關於我可能做錯什麼的想法?

謝謝!

這裏是提供基於答案更新後的代碼:

[SqlFunction] 
public static SqlInt32 RegExIndex(SqlChars input, SqlString pattern, SqlInt32 beginning) 
{ 
    Regex regex = new Regex(pattern.Value, Options); 
    return beginning.Value > input.Value.Length ? 0 
     : !regex.Match(new string(input.Value), beginning.Value < 1 ? 0 : beginning.Value - 1).Success ? 0 
     : regex.Match(new string(input.Value), beginning.Value < 1 ? 0 : beginning.Value - 1).Index + 1; 
} 

回答

2

您使用此Regex.Match過載能力:

public Match Match(
    string input, 
    int startat 
) 

其中startat參數(您beginning參數)是一個從零開始的在哪個字符位置開始搜索。此外,Match.Index屬性(您的match.Index值)也是從零開始的原始字符串中找到捕獲的子字符串的位置

這意味着,在所有的測試,你得到正確的結果:

select dbo.RegExIndex('test', 't', 1) 

最後t(指數= 3)相匹配;

select dbo.RegExIndex('test', 't', 4) 

不匹配任何東西;

select dbo.RegExIndex('test', 't', 0) 

第一t(指數= 0)相匹配。