2012-05-16 3 views
1

나는 많은이 : 나는 자바 소스 코드에서 모든 모델 개체를 retreive 필요간단한 자바 정규 표현식

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

을하지만 난 선언을 완료하고 싶지 않아요. 나는 단지 목표 선언을 원한다.

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

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

내가 instanciation을 얻을 수 있어요 :

나는 (strLine가 InputStreamReader의 String 라인이다) 정규식으로 시도했다. 하지만 뭔가를 할 것이지만, 개체 선언 (전에 "=").

어떻게하면됩니까?

나는 그것을

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

을 할 수 있지만 실제 정규식 아니다.

+1

을 이것은 결코 안정적으로 작동하지 않습니다. 완전히 정확한 결과를 원하면 올바른 Java 파서를 사용해야합니다. 다음 코드에 대해 주석을 달았습니다 :'FooModel f = new FooModel();/* 새로운 FooModel() * /'을 만드시겠습니까? – Joe

+0

예, 작동하지 않을 것입니다. 그러나 어떻게이 작업을 수행 할 수 있습니까? –

+0

m.group (1) 대신 m.group (0) – dragon66

답변

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 
0
(\\w+ \\w+)\\s*=.*new.*Model.*