2012-02-20 3 views
1

안녕하세요 저는 다음 코드가있는 정규식을 사용하여 문자열의 구문을 검색하려고합니다. 모든 두 단어 구문을 찾지 못하는 것 같습니다.자바에서 사용자 정규 표현식을 찾으려면

public static void main(String[] args) { 
    String inputText = "test and test Test hello hello hello test test hello hello "; 

    //Pattern pattern = Pattern.compile("((\\w{3,}?)\\W(\\w{3,}?)\\W).*\\2\\W\\3", Pattern.CASE_INSENSITIVE); 

    Pattern twoWordPrasePattern = Pattern.compile("(([a-zA-Z]{3,})\\W([a-zA-Z]{3,})\\W).*\\2\\W\\3", Pattern.CASE_INSENSITIVE); 

    Matcher matcher = twoWordPrasePattern.matcher(inputText);  
    while (matcher.find()) { 

     System.out.println(inputText.substring(matcher.start(), matcher.end())); 

     System.out.println(matcher.group(1)); 

    } 

} 

안녕하세요 hello 그룹이 퇴장하지 않는 이유는 무엇입니까? 도움을 주신 데 감사드립니다. 어떻게 모든 문구를 찾기 위해 패턴을 바꿀 수 있습니까? Richard

답변

3

matcher.find()은 항상 이전 경기가 중단 된 부분부터 검색합니다. 첫 번째 호출이 발견 : 그래서 모든 것을에서 검색 남은

test Test hello hello hello test test 

가 마지막에

hello hello 

입니다. 그 최종 hello hello은 귀하의 패턴과 일치하지 않습니다 (두 단어 만 있고 패턴에 단어가 4 개 이상 필요합니다 : 두 단어를 그룹 23으로 잡고 나중에 \2\W\3을 찾음) 산출.

+0

감사합니다 ruakh, 그게 어떻게 지금 모든 문구를 찾기 위해 패턴을 변경할 수 있습니다 설명 – Richard

관련 문제