简单的Java正则表达式

时间:2012-05-16 15:01:02

标签: java regex

我有很多:

FooModel f = new FooModel();
..
Bar Model b = new BarModel();

我需要从Java源代码中检索任何模型对象,但我不想完成声明。我只想要对象宣言。

我尝试使用正则表达式(其中strLine是InputStreamReader中的String行):

String pattern = ".*Model (.+)";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(strLine);

if(m.find())
    System.out.print(m.group(1) + "\n");

我能够获得实例化。但我会做同样的事情,但对于对象声明(在“=”之前)。

我该怎么做?

我可以做到

m.group(0).replace(m.group(1),"");

但它不是真正的正则表达式。

2 个答案:

答案 0 :(得分:0)

(\\w+ \\w+)\\s*=.*new.*Model.*

答案 1 :(得分:0)

如果您在一行中有一个启动声明:

import java.util.regex.*;

class  FindModel
{
    public static void main(String[] args) 
    {
        String s = "  FooModel f = new FooModel();";
        String pattern = "([^\\s]*?Model[^=]*)=";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(s);

        if(m.find())
            System.out.print(m.group(1) + "\n");
     }
}

如果一行中有多个语句:

import java.util.regex.*;

class  FindModel
{
    public static void main(String[] args) 
    {
        String s = "  FooModel f = new FooModel();int i=0,j; BarModel b = new BarModel();";
        String pattern = "([^;\\s]*?Model[^=]*)=.*?;";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(s);

        while(m.find())
            System.out.print(m.group(1) + "\n");
     }
}

输出:

FooModel f
BarModel b
相关问题