用于验证SQL Server中的表名的正则表达式(数据库兼容性级别120)

新泽西州

我正在尝试使用此Stack Overflow答案来验证表/列的名称,但是它不起作用。

对于ValidateTableName("18_18_mapped"),它返回false但是,ValidateTableName("mappingStorage_f9dc07dbca414e2d86db00114a9104a3")它会返回true

验证表/列名的任何输入将很有帮助。

static void Main(string[] args)
{
    bool temp = ValidateTableName("18_18_mapped"); // Returns false
    ...
}

private static bool ValidateTableName(string tableName)
{
    string regexForTableName = @"^[\p{L}_][\p{L}\p{N}@$#_]{0,127}$";
    return Regex.IsMatch("[" + tableName + "]", regexForTableName);
}   
威克多·斯特里比尤

不要添加方括号:

return Regex.IsMatch(tableName, regexForTableName);

模式中的方括号对于表示字符类是必需的。这些不是文字方括号。

另外,我将在方法之外声明/编译正则表达式以提高效率:

private static readonly Regex regexForTableName = new Regex(@"^[\p{L}_][\p{L}\p{N}@$#_]{0,127}$");

private static bool ValidateTableName(string tableName)
{
    return regexForTableName.IsMatch(tableName);
}   

编辑

根据MSDN,这些是数据库标识符规范我找不到任何说明第一个字符可以是数字的规范。但是,如果需要允许,请添加\p{N}模式:

^(?:[\p{N}\p{L}_][\p{L}\p{N}@$#_]{0,127}|\[.{1,126}\])$

我要添加\[.{1,126}\]支持所有包含在中的名称[],并且它们的长度必须为128个字符。正则表达式仅匹配非临时表名。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章