0

标题我的意思是公共类声明总是相同的,但名称不同:

public class <class name>

我想搜索公共类的 Java 源代码(在 JTextArea 中)。

所以首先它会发现:

public class Example1public class Example2public class Example3

ETC..

然后我想存储字符串Example1Example2Example3

该程序将用 Java 编写。

谁能帮我吗?

更新:

试了一下,对 Pattern 和 Matcher 类非常陌生。

private String findPublicClass() {
    Pattern pattern = Pattern.compile("\\s*public\\s+class\\s+(\\w+)");
    Matcher matcher = pattern.matcher(txtSource.getText());
    String s = null;
    boolean found = false;
    while (matcher.find()) {
        s = matcher.group(1);
        found = true;
    }
    if(!found)
        System.out.println("No public class found.");
    return s;
}
4

3 回答 3

3

我的建议是学习Java 教程中关于正则表达式的课程。

于 2013-03-31T16:28:54.580 回答
-1

由于名称不同,因此常量部分是“public class”,它具有固定长度,例如 10。因此,您始终可以使用 substring(10) 获取您的类名。

希望有帮助。

编辑:

示例代码

If(line.contains("public class"))
  return line.substring(10);
于 2013-03-31T16:25:45.887 回答
-1

Well, a quick and dirty and very fast approach would be to read the string with a loop running from location 0 to L-1 (length), and have an index "i" stating how many characters were matched.

Every time a character is matched you would i++, otherwise i=0;

This way when i equals the length of the looked-for string, you will have a match. The remainder is the other part (variable part) you are looking for.

Hope this helps!

于 2013-03-31T16:34:24.807 回答