2012-02-22 35 views
6

我想在給定的代碼中找到任何方法調用。所以我用分號分隔代碼作爲分隔符。所以最後我有興趣找到在給定代碼中調用的方法的名稱。我需要一個正則表達式來匹配方法調用模式。請幫忙!!找到方法調用的正則表達式

+0

如果你想要一個正確的解決方案,那麼答案是:這實際上是不可能的。 – biziclop 2012-02-22 21:46:42

+2

不僅實用,而且甚至是理論上的。 Java(語言)不是常規語言,因此它不能被正則表達式解析。 – 2012-02-22 21:49:13

+1

同意;這是令人難以置信的混亂。您必須匹配:實例上的裸函數調用和函數調用,而不是函數定義。另外,你將如何處理嵌套在函數調用中的函數調用,例如'map.get(map.get(123))'?啊。 – beerbajay 2012-02-22 21:51:50

回答

0

我曾經想知道一個字符串是否包含一個Java方法調用(包括包含非ASCII字符的方法名)。

以下工作對我來說很好,但它也找到構造函數調用。希望能幫助到你。

/** 
* Matches strings like {@code obj.myMethod(params)} and 
* {@code if (something)} Remembers what's in front of the parentheses and 
* what's inside. 
* <p> 
* {@code (?U)} lets {@code \\w} also match non-ASCII letters. 
*/ 
public static final Pattern PARENTHESES_REGEX = Pattern 
     .compile("(?U)([.\\w]+)\\s*\\((.*)\\)"); 

/* 
* After these Java keywords may come an opening parenthesis. 
*/ 
private static List<String> keyWordsBeforeParens = Arrays.asList("while", "for", "if", 
     "try", "catch", "switch"); 

private static boolean containsMethodCall(final String s) { 
    final Matcher matcher = PARENTHESES_REGEX.matcher(s); 

    while (matcher.find()) { 
     final String beforeParens = matcher.group(1); 
     final String insideParens = matcher.group(2); 
     if (keyWordsBeforeParens.contains(beforeParens)) { 
      System.out.println("Keyword: " + beforeParens); 
      return containsMethodCall(insideParens); 
     } else { 
      System.out.println("Method name: " + beforeParens); 
      return true; 
     } 
    } 
    return false; 
} 
1

對於合格呼叫{即調用以這種形式:[對象名|的className] .methodName(..)},我已經使用:

(\.[\s\n\r]*[\w]+)[\s\n\r]*(?=\(.*\)) 

當不合格的呼叫存在{即,以這種形式調用:methodName(..)},我一直在使用:

(?!\bif\b|\bfor\b|\bwhile\b|\bswitch\b|\btry\b|\bcatch\b)(\b[\w]+\b)[\s\n\r]*(?=\(.*\)) 

雖然,這也會找到構造函數。

0
File f=new File("Sample.java"); //Open a file 
String s; 
FileReader reader=new FileReader(f); 
BufferedReader br=new BufferedReader(reader); //Read file 
while((s=br.readLine())!=null){ 
    String regex="\\s(\\w+)*\\(((\\w+)*?(,)?(\\w+)*?)*?\\)[^\\{]"; 
    Pattern funcPattern = Pattern.compile(regex); 
    Matcher m = funcPattern.matcher(s); //Matcher is used to match pattern with string 
    if(m.find()){ 
     System.out.printf(group(0)); 
    } 
} 
+1

通常增加一些關於這個代碼如何解決給定問題的描述是一個好主意。請[編輯]您的答案以添加此類說明。 – 2017-02-18 18:41:20