开发者

Code Review: CLR RegexSubstring

Could this be better? .NET 2.0 compatibility for SQL Server 2005:

public static SqlString RegexSubstring(SqlString regexpattern, 
                      开发者_StackOverflow中文版                 SqlString sourcetext, 
                                       SqlInt32 start_position)
{
   SqlString result = null;

   if (!regexpattern.IsNull && !sourcetext.IsNull && !start_position.IsNull)
   {
      int start_location = (int)start_position >= 0 ? (int)start_position : 0;

      Regex RegexInstance = new Regex(regexpattern.ToString());
      result = new SqlString(RegexInstance.Match(sourcetext.ToString(), 
                                                 start_location).Value);
   }

   return result;
}

This is my first attempt at writing CLR functions/etc for SQL Server - is it absolutely necessary to use SqlString/etc data types for parameters?


Just running it through Refactor/Pro

gave this:

public static SqlString RegexSubstring(SqlString regexpattern,
                               SqlString sourcetext,
                               SqlInt32 start_position) {
    if (regexpattern.IsNull || sourcetext.IsNull || start_position.IsNull)
        return null;

    Regex RegexInstance = new Regex(regexpattern.ToString());

    return new SqlString(RegexInstance.Match(sourcetext.ToString(),
                                               (int)start_position).Value);
}

Note that start_location is unused, so possibly you're ignoring warnings?

Another thing is just a matter of style, but can the function be written to not have a dependency on SqtTypes? Then the code becomes:

    private static string RegexSubstring(string regexpattern, string sourcetext, int start_position) {

        if (regexpattern == null || sourcetext == null || start_position == null)
            return null;

        Regex RegexInstance = new Regex(regexpattern);
        return RegexInstance.Match(sourcetext, start_position).Value;
    }

and call it with :

new SqlString(RegexSubstring(regexpattern.ToString(), sourcetext.ToString(), start_position))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜