Parsing Java code with Java

前端 未结 5 1230
予麋鹿
予麋鹿 2021-01-29 11:32

Is it possible to parse some Java code with a regex?

So let\'s say I want a list of the int variables from this:



        
相关标签:
5条回答
  • 2021-01-29 11:52

    I would recommend you look into parser generators, eg. JavaCC. JavaCC lets you describe the grammar in an BNF-like style and creates Java classes according to it. There are also already grammars available for JavaCC to parse Java code, I think even as an example or tutorial that comes with JavaCC.

    0 讨论(0)
  • 2021-01-29 12:07

    People often try to parse HTML, XML, C or java with regular expressions.

    With enough efforts and tricks, lot of amazing things are possible with complex combinations of regex. But you always end up with something very incomplete and not efficient.

    Regex can't handle complex grammars, use a parser, either generic or specific to java.

    0 讨论(0)
  • 2021-01-29 12:09

    If you really have to use regex then try something like (?<=int )\\w+, but I strongly advise using some Java parser.

    0 讨论(0)
  • 2021-01-29 12:12

    You can try with regular expressions, but it may be easier to user a Java Parser. You can try JavaCC.

    0 讨论(0)
  • 2021-01-29 12:14

    You would probably want to use a more advanced grammar parsing application than regex. You could for example look into ANTLR which also has various grammars available.

    0 讨论(0)
提交回复
热议问题