2012-12-11 26 views
1

拋出異常下面的代碼拋出正則表達式[]上運行

關於「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) 
     {}}} 
+0

閱讀的InnerException。 – SLaks

+2

一些數組中的正則表達式是錯誤的,如果你刪除初始化,並嘗試初始化所有的人都在main(),你會發現一個。 – nothrow

+0

爲什麼你寫的是什麼,真正臃腫'「+ Regex.Escape(‘[’)+」',而不僅僅是'\ [ '? –

回答

3

在4正則表達式

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

打開(在最後。這是不被關閉!

+0

正確答案+1 –

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

...但你應該檢查。

+0

+ 0是什麼,他括號中的問題? –

+0

是的,他打開了一個從未關閉的連接。 –

+1

@SamIam:我認爲這* *是合理的留到OP ...但我會提出一些建議。 –