Code review: CLR RegexSubstring
Could it be better? .NET 2.0 Compatibility for SQL Server 2005:
public static SqlString RegexSubstring(SqlString regexpattern,
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 / etc functions for SQL Server - is it absolutely necessary to use SqlString / etc datatypes for parameters?
+2
a source to share
1 answer
Just run it through Refactor / Pro
gave the following:
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 not used, so perhaps you are ignoring the warnings?
The other thing is just a matter of style, but is it possible to write a function so that it doesn't depend 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))
+1
a source to share