Skip to main content
 首页 » 编程设计

c#之正则表达式 [] 在运行时抛出异常

2024年01月21日32zhujiabin

下面的代码抛出

The type initializer for 'ConsoleApplication1.Program' threw an exception.

在线

public static Regexp[] keepers = { ... }; 

为什么这是错误的,我该如何解决?

namespace ConsoleApplication1 
{ 
    class Program 
    { 
        public static String output = ""; 
        public static Regex[] keepers = {  
                                            new Regex(@"using(?<everythingElse> [a-zA-Z.]+;)"), 
                                            new Regex(@"namespace(?<everythingElse> [a-zA-Z._]+)"), 
                                            new Regex(@"class(?<everythingElse> [a-zA-Z._]+)"), 
                                            new Regex(@"(public|private)? ?(static)? ?(?<type> String|void|int|Double)(" + Regex.Escape("[") + "?" + Regex.Escape("]") + "?" + "(?<functionName> [a-z_]+)(?<params> [^\r\n]+)") 
                                        }; 
        [STAThread] 
        static void Main(string[] args) 
        {}}} 

请您参考如下方法:

总是 查看完整的异常。这是你的情况(稍微重新格式化):

Unhandled Exception: System.TypeInitializationException: The type initializer for 
'ConsoleApplication1.Program' threw an exception. ---> System.ArgumentException: 
 parsing "(public|private)? ?(static)? ?(?<type> String|void|int|Double)(\[?]? 
 (?<functionName> [a-z_]+)(?<params> [^]+)" - Not enough )'s. 
   at System.Text.RegularExpressions.RegexParser.ScanRegex() 
   at System.Text.RegularExpressions.RegexParser.Parse(String re, RegexOptions op) 
   at System.Text.RegularExpressions.Regex..ctor(String pattern, RegexOptions options, TimeSpan matchTimeout, Boolean useCache) 
   at System.Text.RegularExpressions.Regex..ctor(String pattern) 
   at ConsoleApplication1.Program..cctor() 
   --- End of inner exception stack trace --- 
   at ConsoleApplication1.Program.Main(String[] args) 

所以你可以看到:

  • 在第四个正则表达式中
  • 你的括号有问题

接下来,我会尝试将那个大的正则表达式分解成小的正则表达式,并弄清楚为什么您有一个不匹配的括号。我怀疑是这样的:

"(" + Regex.Escape("[") + "?" + Regex.Escape("]") + "?" 

应该是:

"(" + Regex.Escape("[") + "?" + Regex.Escape("]") + ")?" 

...但是你应该检查一下。