我有很多:
FooModel f = new FooModel();
..
Bar Model b = new BarModel();
我需要从 Java 源代码中检索任何模型对象,但我不想完成声明。我只想要对象声明。
我尝试使用正则表达式(其中 strLine 是 InputStreamReader 中的字符串行):
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),"");
但这不是真正的正则表达式。
最佳答案
如果您在一行中有一个启动声明:
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
关于java - 简单的Java正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10621281/