我有一個程序,其中包含許多字符串常量,用于通過正則表達式允許特定字符。我現在有一個我想在所有地方阻止的字符列表,但我不想回過頭來檢查我所有的舊字符串常量并重寫它們。相反,我想創建一個受限字符列表并只在一個地方編輯該列表(以防將來發生變化)。然后,我將通過自定義正則表達式運行所有字符串常量。我有 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 關注
- 83 瀏覽
添加回答
舉報
0/150
提交
取消