获得正确的正则表达式 - Java

时间:2012-04-25 18:02:45

标签: java regex

我正在尝试解析cflow的输出,然后将其用于构建控制流的3D图。 cflow的输出看起来像这样:

main() <int main (int argc, char *argv[]) at sort.c:3>:
    strcmp()
    printf()
    malloc()
    getline() <char *getline (int max) at sort.c:62>:
        isspace()
        getchar()
        ungetc()
        malloc()
    qsort()
    free()

我正在使用正则表达式来提取函数名称和括号 - 我想得到main()strcmp()等。我的代码如下:

String line = input.nextLine(); // input is a Scanner reading from a file
Pattern p = Pattern.compile("[a-zA-Z0-9_]+\\(\\)"); // the important part
Matcher m = p.matcher(line);

现在,我正在使用的模式使用Emacs的regexp-builder模式。然而,当我运行这个程序时,我没有得到任何匹配。我可能只是不了解Java的正则表达式函数。

另外,我意识到显而易见的解决方案是不使用Java ......我更喜欢这样,但是我要用Processing绘制图形,所以我真的没有选择。

2 个答案:

答案 0 :(得分:1)

如果您尝试提取部分字符串,则必须使用括号在正则表达式中形成组。如果您将正则表达式重写为.*([a-zA-Z0-9_]+\\(\\)).*,则字面括号中的组实际上存储为匹配项。然后,您可以调用m.group(1)来检索由第一个括号组提取的字符串,即[a-zA-Z0-9_]+\\(\\)

答案 1 :(得分:0)

使用您当前的语法和m.matches(),Java假定您的意思是:

Pattern p = Pattern.compile("^[a-zA-Z0-9_]+\\(\\)$");

所以,你需要在表达式的开头和结尾添加通配符(我在括号中包装了你想要匹配的部分)

Pattern p = Pattern.compile(".*([a-zA-Z0-9_]+\\(\\)).*");

或致电m.find()而非m.matches()

您现在可以致电:

if(m.matches())
{
    myFunctionName = m.group(1);
}