Parsing Java code with Java


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:

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

And I want to put these into 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);

        String match =;
        Pattern p2 = Pattern.compile();//Here as well
        Matcher m2 = p.matcher(s);
            for(int i = 0; i < m.groupCount()){
                //add the variables to the lists

What I am asking is what regex could possibly handle this task?

The reason for all this is so the user can take a bit of control over the application using a bit of code (an Android Application btw)

If it isn't recommended to use a regex, then what parser should I be using?


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.