Parse CIL code with Regex

匆匆过客 提交于 2019-12-19 10:58:09

问题


I have a *.il file. I want to find all non-empty methods in it (.method). For example:

.class private auto ansi beforefieldinit MyApp.Program
       extends [mscorlib]System.Object
{
   //catch its body
  .method private hidebysig static void  Main(string[] args) cil managed
  {
    .entrypoint
    // 
    .maxstack  8
    IL_0000:  nop
    IL_0001:  ret
  }  

  //catch its body
  .method public hidebysig specialname rtspecialname 
          instance void  .ctor() cil managed
  {
    // 
    .maxstack  8
    IL_0000:  ldarg.0
    IL_0001:  call       instance void [mscorlib]System.Object::.ctor()
    IL_0006:  ret
  }  

   //don't touch, it's empty
   .method public hidebysig newslot virtual 
          instance string  Invoke(string a) runtime managed
  {
  }  
 //......................................
}

Now I'm doing that using class string. It's quite nonrational. I tried using Regex but I could not figure out how to create a reg expression to catch only

  • methods (and not classes)
  • only methods with non-empty body

Does anybody can help me?


回答1:


Using regex for parsing structure code is not recommended and it is bad practice

Try to use regex pattern

(\.method\s[^{]+?)(?=\s*{)(?!\s*{\s*})

Test it here.

To catch also the body {...} of each method, use regex pattern

(\.method\s[^{]+{(?!\s*}).*?})

Test it here.


To learn more about regular expressions visit regular-expressions.info



来源:https://stackoverflow.com/questions/12999422/parse-cil-code-with-regex

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!