将旧的正则表达式模式传递给新的自定义正则表达式以排除特定字符

时间:2019-04-09 22:01:03

标签: c# regex

我有一个程序,其中有很多字符串常量,用于通过正则表达式允许特定字符。现在,我有了要在任何地方阻止的字符列表,但我不想再遍历所有旧的字符串常量并重写它们。相反,我想创建受限字符列表并仅在一个位置(以防将来更改)编辑该列表。然后,我将通过自定义的正则表达式运行所有字符串常量。

我有在web.config中定义的受限字符列表,如下所示:

<add key="RestrChar" value="\!#%&lt;&gt;|&amp;;"/>

像这样调用自定义正则表达式:

[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 个答案:

答案 0 :(得分:0)

实际上知道了我要做什么:

int indexPropRegex = propRegex.IndexOf('^');
string restrictedCharsAction = "(?!.*[" + restricedChars + "]);
propRegex = indexPropRegex == -1 ? propRegex.Insert(0, restrictedCharsAction) : propRegex.Insert(indexPropRegex +1, restrictedCharsAction);
return propRegex;