使用Java解析Java代码 [英] Parsing Java code with Java
问题描述
是否可以用正则表达式解析一些Java代码?
Is it possible to parse some Java code with a regex?
所以假设我想要一个 int $ c的列表$ c>这里的变量:
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;
我想将这些放入 ArrayList
。
这样的事情:
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?
所有这一切的原因是用户可以采取一些控制使用一些代码的应用程序(Android应用程序btw)
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?
推荐答案
人们经常尝试使用正则表达式解析HTML,XML,C或java。
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.
正则表达式无法处理复杂的语法,使用解析器,通用或特定于java 。
Regex can't handle complex grammars, use a parser, either generic or specific to java.
这篇关于使用Java解析Java代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!