Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

regex - 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);

    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 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...