Parsing Java Code Using Java

Is it possible to parse some Java code with regular expression?

So, let's say I need a list of int variables from this:

 int abc1 = 1; int abc2 = abc1 + 1; int abd3 = abc1 + abc2; 

And I want to put them in an ArrayList .

So something like this:

 private void parse(String s){ List<List<String>> variables = new ArrayList<List<String>>(); list.add(new ArrayList<String>);//var type list.add(new ArrayList<String>);//var name list.add(new ArrayList<String>);//var data Pattern p = Pattern.compile();//This is what I want Matcher m = p.matcher(s); while(m.find()){ String match = m.group(); Pattern p2 = Pattern.compile();//Here as well Matcher m2 = p.matcher(s); while(m2.find()){ for(int i = 0; i < m.groupCount()){ //add the variables to the lists } } } } 

What I'm asking is that regex can solve this problem?


The reason for all this is that the user can have a little control over the application using a bit of code (Android app for Android)

If regex is not recommended, then which parser should I use?

-2
source share
5 answers

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

With enough effort and tricks, many amazing things can be done with complex combinations of regular expressions. But you always get something very incomplete and ineffective.

Regex cannot process complex grammars, use a parser, either general or specific to java .

+4
source

You can try using regular expressions, but it might be easier for the user to use Java Parser. You can try JavaCC .

+4
source

You might want to use a better grammar analysis application than regular expression. For example, you can look at ANTLR , which also has various grammars available.

+4
source

If you really need to use a regular expression, try something like (?<=int )\\w+ , but I highly recommend using some Java parser.

+2
source

I would recommend you look at parser generators, for example. JavaCC. JavaCC allows you to describe BNF-style grammar and create Java classes to fit it. There are also existing grammars for JavaCC for analyzing Java code, I think, even as an example or guide that comes with JavaCC.

+1
source

All Articles