2015-09-17 26 views
0

我想從java代碼中提取所有方法調用。我寫了以下兩個正則表達式,但它們無法提取所有方法調用。從java代碼中提取方法調用

Reg1中:Pattern.compile("([a-zA-Z][0-9_a-zA-Z]*\\([a-zA-Z0-9_\\s,\\[\\]\\(\\)\\.]+\\))");

的Reg2:Pattern.compile("([a-zA-Z][0-9_a-zA-Z]*\\([\\s]*\\))")

輸入:

"{ 
    if ((war == null) && (config != null)) { 
    sb.append(&config=); 
    sb.append(URLEncoder.encode(config,getCharset())); 
    } 
    if ((war == null) && (localWar != null)) { 
    sb.append(&war=); 
    sb.append(URLEncoder.encode(localWar,getCharset())); 
    } 
    if (update) { 
    sb.append(&update=true); 
    } 
    if (tag != null) { 
     sb.append(&tag=); 
     sb.append(URLEncoder.encode(tag,getCharset())); 
    } 
    }" 

輸出:

getCharset getCharset getCharset append append append 

我不能夠提取 「encode」。

有沒有人有任何想法作爲我應該添加到正則表達式?

+5

這是(根據語言理論的行之有效的原則)不可能做到的使用正則表達式,這主要是因爲每次調用可能包含通話這可能包含呼... – laune

+0

請給我建議一些替代它。 – Sangeeta

+2

也許這篇文章的任何幫助http://stackoverflow.com/questions/2206065/java-parse-java-source-code-extract-methods – Mariano

回答

6

您需要一個Java代碼解析器來執行此任務。下面是使用Java Parser一個例子:

public class MethodCallPrinter 
{ 
    public static void main(String[] args) throws Exception 
    { 
     FileInputStream in = new FileInputStream("MethodCallPrinter.java"); 

     CompilationUnit cu; 
     try 
     { 
      cu = JavaParser.parse(in); 
     } 
     finally 
     { 
      in.close(); 
     } 
     new MethodVisitor().visit(cu, null); 
    } 

    private static class MethodVisitor extends VoidVisitorAdapter 
    { 
     @Override 
     public void visit(MethodCallExpr methodCall, Object arg) 
     { 
      System.out.print("Method call: " + methodCall.getName() + "\n"); 
      List<Expression> args = methodCall.getArgs(); 
      if (args != null) 
       handleExpressions(args); 
     } 

     private void handleExpressions(List<Expression> expressions) 
     { 
      for (Expression expr : expressions) 
      { 
       if (expr instanceof MethodCallExpr) 
        visit((MethodCallExpr) expr, null); 
       else if (expr instanceof BinaryExpr) 
       { 
        BinaryExpr binExpr = (BinaryExpr)expr; 
        handleExpressions(Arrays.asList(binExpr.getLeft(), binExpr.getRight())); 
       } 
      } 
     } 
    } 
} 

輸出:

Method call: parse 
Method call: close 
Method call: visit 
Method call: print 
Method call: getName 
Method call: getArgs 
Method call: handleExpressions 
Method call: visit 
Method call: handleExpressions 
Method call: asList 
Method call: getLeft 
Method call: getRight 
+0

主要困難是處理句子中的遞歸。您可以將其添加到您的答案中,例如另一個表達式的訪問者。 – laune

+0

@laune你說「句子遞歸」是什麼意思? – splash

+1

Java語法定義瞭如何構造語言的「句子」。在「方法調用」的定義中,通過中間的一些NT,「方法調用」再次出現:遞歸。 - 所以必須爲(表達式e:methodCall.getArgs()){...}'迭代'等。 – laune