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

Jor*_*nor 1 c# regex

以下代码抛出

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

在线上

public static Regexp[] keepers = { ... };
Run Code Online (Sandbox Code Playgroud)

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

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)
        {}}}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 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)
Run Code Online (Sandbox Code Playgroud)

所以你可以看到:

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

接下来,我会尝试将那个大的正则表达式分解成小的表达式,并弄清楚为什么你有一个无与伦比的支架.我怀疑这个:

"(" + Regex.Escape("[") + "?" + Regex.Escape("]") + "?"
Run Code Online (Sandbox Code Playgroud)

应该:

"(" + Regex.Escape("[") + "?" + Regex.Escape("]") + ")?"
Run Code Online (Sandbox Code Playgroud)

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