java - 简单的Java正则表达式

标签 java regex

我有很多:

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/

相关文章:

java - 使用 postman 解析和映射 json

java - 如何测试这条 Camel 路线?依赖注入(inject)和环境变量

java - Hamcrest 比较系列

java - 变量不会更新(在 Java 中)

正则表达式上的 Python 拆分字符串

javascript - 字符串用正则表达式分割,返回完全匹配的数组

Java:使用 splitText() 方法分割节点

java - 方法住在哪里?栈还是堆?

regex - 在 Kotlin 中查找模式每次出现的位置

javascript - 像 12,345,678,900 这样的字符串的正则表达式模式?