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

时间:2012-12-11 17:32:51

标签: c# regex

以下代码抛出

  

'ConsoleApplication1.Program'的类型初始化程序引发了异常。

就行了

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)
        {}}}

2 个答案:

答案 0 :(得分:6)

始终查看完整的例外情况。在这种情况下(稍微重新格式化):

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("]") + ")?"

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

答案 1 :(得分:3)

在4.正则表达式中

@"(public|private)? ?(static)? ?(?<type> String|void|int|Double)(

打开一个(最后。这个没有被关闭!

相关问题