2014-07-11 3 views
1

하자를 추출 우리가 어떤 문장을 말한다.자바 정규식 여러 그룹이 일치 &

정규 표현식을 사용하여 특정 문장을 모두 일치시키는 방법을 알고 있습니까?

+1

당신은 아무것도 시도? –

+0

http://stackoverflow.com/questions/6020384/create-array-of-regex-matches –

답변

9

사용 Matcher.find.

import java.io.IOException; 
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

public class App { 

    public static void main(String[] args) throws IOException { 

     String s = "Hello my name is Neo and my company brand name is Company Country1. " 
       + "But we have also other companies like Company Country2 (in Europe), " 
       + "and also Company Country3 (in Asia)"; 

     Pattern pattern = Pattern.compile("Company Country\\d"); 
     Matcher matcher = pattern.matcher(s); 
     while (matcher.find()) { 
      String group = matcher.group(); 
      System.out.println(group); 
     } 
    } 
} 

출력 :

Company Country1 
Company Country2 
Company Country3 
1
public static void main(String[] args) { 
String s="Hello my name is Neo and my company brand name is Company Country1. But we have also other companies like Company Country2 (in Europe), and also Company Country3 (in Asia)"; 
Pattern p = Pattern.compile("(Company Country\\d)"); // just match Company followed by CountryX - literally. 
Matcher m = p.matcher(s); 

while(m.find()){ 
    System.out.println(m.group(1)); // catch the first group 
} 


} 

O/P :

Company Country1 
Company Country2 
Company Country3