我有一個(gè)程序,其中包含許多字符串常量,用于通過正則表達(dá)式允許特定字符。我現(xiàn)在有一個(gè)我想在所有地方阻止的字符列表,但我不想回過頭來檢查我所有的舊字符串常量并重寫它們。相反,我想創(chuàng)建一個(gè)受限字符列表并只在一個(gè)地方編輯該列表(以防將來發(fā)生變化)。然后,我將通過自定義正則表達(dá)式運(yùn)行所有字符串常量。我有 web.config 中定義的受限字符列表,如下所示:<add key="RestrChar" value="\!#%<>|&;"/>像這樣調(diào)用自定義正則表達(dá)式:[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}]+", ""); }}現(xiàn)在,當(dāng)ConstantStringName特別包含一些我想排除的字符時(shí),它就可以工作了,如下所示:public const string ConstantStringName = "^[-a-z A-Z.0-9/!&\"()]{1,40}$";!并且&被明確包含在內(nèi),因此它們將被替換為任何東西。但是如果我試圖排除的字符沒有明確列出而是通過這樣的列表包含在內(nèi),這將不起作用:public const string ConstantStringName = "^[ -~\x0A\x0D]{1,40}$";我試過像這樣添加一個(gè)負(fù)面的前瞻: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;}我又一次失敗了。有沒有人有任何其他想法,無論將哪組正則表達(dá)式規(guī)則傳遞到我的自定義正則表達(dá)式中,我都可以實(shí)現(xiàn)排除一組字符的目標(biāo)?
1 回答

飲歌長(zhǎng)嘯
TA貢獻(xiàn)1951條經(jīng)驗(yàn) 獲得超3個(gè)贊
實(shí)際上弄清楚了我要做什么:
int indexPropRegex = propRegex.IndexOf('^');
string restrictedCharsAction = "(?!.*[" + restricedChars + "]);
propRegex = indexPropRegex == -1 ? propRegex.Insert(0, restrictedCharsAction) : propRegex.Insert(indexPropRegex +1, restrictedCharsAction);
return propRegex;
- 1 回答
- 0 關(guān)注
- 82 瀏覽
添加回答
舉報(bào)
0/150
提交
取消