正则表达式交替和顺序mathing

时间:2016-06-09 12:12:18

标签: java regex

因此,预期的行为是,程序输出.java文件中所有类和对象的树。像这样:

class One >
    method one()
    method two()
class Two extends One>
    method three()

等等。我想出了2个正则表达式模式,一个用于一个类,另一个用于方法。

this.classPattern = Pattern.compile("class\\s([a-zA-Z]+)(?:\\sextends\\s([a-zA-Z<>]+))?\\s?\\{");
this.methodPattern = Pattern.compile("([^ new=/\\(\\)][a-zA-Z\\[\\]]*)\\s([a-zA-Z]+)\\((.*)\\)\\s?\\{?(\\;?)");

我被卡住了,无法弄清楚如何成功解析文件。这就是我想出来的,尝试这样做:

Matcher matcher = classPattern.matcher(string);

while (matcher.find()) {
    System.out.println("class > " + matcher.group(1));
    matcher.usePattern(methodPattern);

         while (matcher.find()) {
              System.out.println("\t method > " + matcher.group(2) + " (" + matcher.group(1) + ")");
         }
}

这是我到目前为止的地方。

class > RegExpLanguageHosts
     method > getInstance (RegExpLanguageHosts)
     method > RegExpLanguageHosts (private)
     method > setRegExpHost (void)
     method > findRegExpHost (RegExpLanguageHost)
     method > isRedundantEscape (boolean)
     method > supportsInlineOptionFlag (boolean)
     method > supportsExtendedHexCharacter (boolean)
     method > supportsLiteralBackspace (boolean)
     method > supportsNamedGroupSyntax (boolean)
     method > supportsNamedGroupRefSyntax (boolean)
     method > supportsPythonConditionalRefs (boolean)
     method > supportsPossessiveQuantifiers (boolean)
     method > supportsSimpleClass (boolean)
     method > isValidCategory (boolean)
     method > getAllKnownProperties (String[][])
     method > getPropertyDescription (String)
     method > main (void)
     method > MyExitAction (public)
     method > actionPerformed (void)
     method > MyPackAction (public)
     method > actionPerformed (void)
     method > MySetLafAction (public)
     method > actionPerformed (void)
     method > getKnownCharacterClasses (String[][])
     method > getPosixCharacterClasses (String[][])
     method > something (Logger)
     method > main (void)
     method > MyExitAction (public)
     method > actionPerformed (void)
     method > MyPackAction (public)
     method > actionPerformed (void)
     method > MySetLafAction (public)
     method > actionPerformed (void)

如何替换模式并检测类结束,并将方法分组到特定的类中?

文件中有多个类,但是方法会堆积到第一个类而忽略其他类。

我最接近的是:

RegExpLanguageHosts
     > getInstance
FormPreviewFrame
     > RegExpLanguageHosts
MyExitAction
     > setRegExpHost
MyPackAction
     > findRegExpHost
MySetLafAction
     > isRedundantEscape
FormPreviewFrame
     > supportsInlineOptionFlag
MyExitAction
     > supportsExtendedHexCharacter
MyPackAction
     > supportsLiteralBackspace
MySetLafAction
     > supportsNamedGroupSyntax

        while (classMatcher.find()) {
            System.out.println(classMatcher.group(1));
            if (methodMatcher.find()) {
                System.out.println("\t > " + methodMatcher.group(2));
            }   
        }

0 个答案:

没有答案