繁体   English   中英

使用Regex.CompileToAssembly时如何处理大量RegEx模式?

[英]How to handle large number of RegEx patterns when using Regex.CompileToAssembly?

我正在尝试将正则表达式列表编译为程序集。

我发现每个RegexCompilationInfo对象的“ Name”值必须不同,因此在编译时它们是不同的对象。

但是说我有很多RegEx模式(比如说接近100)。 在其中每个名称上设置名称并保持这些名称似乎很困难。 不仅是每次我要检查每个模式的文本时(我这样做),我都必须知道所有名称,并通过其名称实例化每个对象才能使用它)

有没有更简单的方法来解决这个问题?

        List<RegexCompilationInfo> compilationList = new List<RegexCompilationInfo>();

        compilationList.Add(new RegexCompilationInfo(@"pattern1",RegexOptions.CultureInvariant,"Name1","Namespace.Space",true));
        compilationList.Add(new RegexCompilationInfo(@"pattern2", RegexOptions.CultureInvariant, "Name2", "Namespace.Space", true));
        ...
        ...
        compilationList.Add(new RegexCompilationInfo(@"pattern100", RegexOptions.CultureInvariant, "Name100", "Namespace.Space", true));

        // Apply AssemblyTitle attribute to the new assembly
        //
        // Define the parameter(s) of the AssemblyTitle attribute's constructor 
        Type[] parameters = { typeof(string) };
        // Define the assembly's title
        object[] paramValues = { "Library of compiled regular expressions" };
        // Get the ConstructorInfo object representing the attribute's constructor
        ConstructorInfo ctor = typeof(System.Reflection.AssemblyTitleAttribute).GetConstructor(parameters);
        // Create the CustomAttributeBuilder object array
        CustomAttributeBuilder[] attBuilder = { new CustomAttributeBuilder(ctor, paramValues) };

        // Generate assembly with compiled regular expressions
        RegexCompilationInfo[] compilationArray = new RegexCompilationInfo[compilationList.Count];
        AssemblyName assemName = new AssemblyName("RegexLib, Version=1.0.0.1001, Culture=neutral, PublicKeyToken=null");
        compilationList.CopyTo(compilationArray);
        Regex.CompileToAssembly(compilationArray, assemName, attBuilder);   

用法

  Name1 name1Regex = new Name1(); 
  Name2 name2Regex = new Name2();
  ..
  ...

  if (name1Regex.Matches(text).Count > 0)

为了命名模式,您可以仅使用递增索引。 "name" + index

您可以使用反射将所有模式加载到列表中

var asm = Assembly.Load("RegexLib, Version=1.0.0.1001, Culture=neutral, PublicKeyToken=null");
var patterns = new List<Regex>();
foreach (var type in asm.GetExportedTypes())
{
    if (typeof(Regex).IsAssignableFrom(type))
    {
        patterns.Add((Regex) Activator.CreateInstance(type));
    }
}
return patterns;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM