我有一个程序,其中包含许多字符串常量,用于通过正则表达式允许特定字符。我现在有一个我想在所有地方阻止的字符列表,但我不想回过头来检查我所有的旧字符串常量并重写它们。相反,我想创建一个受限字符列表并只在一个地方编辑该列表(以防将来发生变化)。然后,我将通过自定义正则表达式运行所有字符串常量。我有 web.config 中定义的受限字符列表,如下所示:<add key="RestrChar" value="\!#%<>|&;"/>像这样调用自定义正则表达式:[RestrictCharRegExpress(ConstantStringName, ErrorMessage = CustomErrMsg)]public string StringName类定义如下:public class RestrictCharRegExpressAttribute : RegularExpressionAttribute{ public RestrictCharRegExpressAttribute(string propRegex) : base(GetRegex(propRegex)){ } private static string GetRegex(string propRegex) { string restrictedChars = ConfigurationManager.AppSettings.Get("RestrChar"); return Regex.Replace(propRegex, $"[{restrictedChars}]+", ""); }}现在,当ConstantStringName特别包含一些我想排除的字符时,它就可以工作了,如下所示:public const string ConstantStringName = "^[-a-z A-Z.0-9/!&\"()]{1,40}$";!并且&被明确包含在内,因此它们将被替换为任何东西。但是如果我试图排除的字符没有明确列出而是通过这样的列表包含在内,这将不起作用:public const string ConstantStringName = "^[ -~\x0A\x0D]{1,40}$";我试过像这样添加一个负面的前瞻:return propRegex + "(?![" + restrictedChars + "])";但这在这两种情况下都不起作用。还尝试了否定集:int i = propRegex.IndexOf(']');if (i != -1){ propRegex = propRegex.Insert(i, "[^" + restrictedChars + "]"); return propRegex;}仍然不适用于这两种情况。最后我尝试了字符类减法:int i = propRegex.IndexOf(']');if (i != -1){ propRegex = propRegex.Insert(i, "-[" + restrictedChars + "]"); return propRegex;}我又一次失败了。有没有人有任何其他想法,无论将哪组正则表达式规则传递到我的自定义正则表达式中,我都可以实现排除一组字符的目标?
1 回答

饮歌长啸
TA贡献1951条经验 获得超3个赞
实际上弄清楚了我要做什么:
int indexPropRegex = propRegex.IndexOf('^');
string restrictedCharsAction = "(?!.*[" + restricedChars + "]);
propRegex = indexPropRegex == -1 ? propRegex.Insert(0, restrictedCharsAction) : propRegex.Insert(indexPropRegex +1, restrictedCharsAction);
return propRegex;
- 1 回答
- 0 关注
- 90 浏览
添加回答
举报
0/150
提交
取消