【发布时间】: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