gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 17:54:53 24 4
gpt4 key购买 nike

下面的代码抛出

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

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

关于c# - 正则表达式 [] 在运行时抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13825441/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com