可能重复:
使用正则表达式解析 CIL 代码
这个问题来自Parse CIL code with Regex
To capture methods' body I added brackets ()
,它变成
var regex3 = @"(\.method\s[^{]+({(?!\s*}).*?}))";
它工作得很好。例如,capture.Groups[2]
给我
{
.entrypoint
//
.maxstack 8
IL_0000: nop
IL_0001: call void TestAssemblyConsole.Test::Method1()
IL_0006: nop
IL_0007: call int32 TestAssemblyConsole.Test::Method2()
IL_000c: pop
IL_000d: call string [mscorlib]System.Console::ReadLine()
IL_0012: pop
IL_0013: ret
}
这就是我要找的。但是,如果我有
.method public hidebysig static void Method1() cil managed
{
//
.maxstack 3
.locals init (class [mscorlib]System.Exception V_0)
IL_0000: nop
.try
{
.try
{
IL_0001: nop
IL_0002: ldstr "gfhgfhgfhg"
IL_0007: call void [mscorlib]System.Console::WriteLine(string)
IL_000c: nop
IL_000d: nop
IL_000e: leave.s IL_0020
} // end .try
catch [mscorlib]System.Exception
{
IL_0010: stloc.0
IL_0011: nop
IL_0012: ldstr "exception"
IL_0017: call void [mscorlib]System.Console::WriteLine(string)
IL_001c: nop
IL_001d: nop
IL_001e: leave.s IL_0020
} // end handler
IL_0020: nop
IL_0021: leave.s IL_0031
} // end .try
finally
{
IL_0023: nop
IL_0024: ldstr "finally"
IL_002f: nop
IL_0030: endfinally
} // end handler
IL_0031: nop
IL_0032: ret
}
那么它就不能很好地工作。由于在方法内,我只是捕获了方法主体的一部分} .. }
{
//
.maxstack 1
.locals init (class [mscorlib]System.Exception V_0)
IL_0000: nop
.try
{
.try
{
IL_0001: nop
IL_0002: ldstr "gfhgfhgfhg"
IL_0007: call void [mscorlib]System.Console::WriteLine(string)
IL_000c: nop
IL_000d: nop
IL_000e: leave.s IL_0020
}
如何更改正则表达式以捕获所有方法的主体,即使它包含许多 { .. } ?