Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...