Bit*_*der 7 c# regex sql t-sql sql-like
我正在寻找将类似SQL语句转换为等效的正则表达式即ie
LIKE '%this%'
LIKE 'Sm_th'
LIKE '[C-P]arsen'
Run Code Online (Sandbox Code Playgroud)
这样做的最佳方法是什么?
PS我想在.Net Framework(C#)上做这件事.
以下正则表达式在MatchEvaluator委托的帮助下将类似SQL的模式转换为正则表达式模式.它正确处理方括号块并转义特殊的正则表达式字符.
string regexPattern = Regex.Replace(
likePattern,
@"[%_]|\[[^]]*\]|[^%_[]+",
match =>
{
if (match.Value == "%")
{
return ".*";
}
if (match.Value == "_")
{
return ".";
}
if (match.Value.StartsWith("[") && match.Value.EndsWith("]"))
{
return match.Value;
}
return Regex.Escape(match.Value);
});
Run Code Online (Sandbox Code Playgroud)