【问题标题】:SQL Server RegExIndex CLR Returning Wrong Index LocationSQL Server RegExIndex CLR 返回错误的索引位置
【发布时间】:2012-11-30 02:03:27
【问题描述】:

我有一个 C# 中的 SQL Server CLR,其功能类似于 SQL Server CHARINDEX 函数,但允许使用正则表达式。

[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;
}

在测试中,我发现下面应该返回1的时候返回3:

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

下面应该返回4的时候返回0:

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;
}

【问题讨论】:

    标签: .net sql-server regex clr


    【解决方案1】:

    你正在使用这个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)。

    【讨论】:

      猜你喜欢
      • 2019-09-07
      • 2013-07-08
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-26
      相关资源
      最近更新 更多