2014-09-30 3 views
1

다음 코드에 큰 문제가 있습니다. 나는 그것이 발견 된 키워드 (바늘) 앞뒤에 n 개의 단어를 반환 할 것으로 기대하지만 절대 그렇지 않습니다. 나는 텍스트가있는 경우텍스트의 주어진 위치 전후에 지정된 단어 수를 반환하십시오.

"There is a lot of interesting stuff going on, when someone tries to find the needle in the haystack. Especially if there is anything to see blah blah blah". 

말 그리고 나는이 정규 표현식이 있습니다

"((?:[a-zA-Z'-]+[^a-zA-Z'-]+){0,5}\b)needle(\b(?:[^a-zA-Z'-]+[a-zA-Z'-]+){0,5})" 

이 정확히 지정된 캐릭터 라인에 바늘을 일치

로 텍스트를 리턴해서는 안됩니다을
someone tries to find the needle in the haystack. Especially if 

절대로 :-(실행 중일 때, 확실히 내 문자열은 빈 문자열을 반환합니다. 키워드가 주어진 텍스트 내에 있습니다.

private String trimStringAtWordBoundary(String haystack, int wordsBefore, int wordsAfter, String needle) { 
    if(haystack == null || haystack.trim().isEmpty()){ 
     return haystack ; 
    } 

    String textsegments = ""; 

    String patternString = "((?:[a-zA-Z'-]+[^a-zA-Z'-]+){0,"+wordsBefore+"}\b)" + needle + "(\b(?:[^a-zA-Z'-]+[a-zA-Z'-]+){0,"+wordsAfter+"})"; 


    Pattern pattern = Pattern.compile(patternString); 
    Matcher matcher = pattern.matcher(haystack); 

    logger.trace(">>> using regular expression: " + matcher.toString()); 

    while(matcher.find()){ 
     logger.trace(">>> found you between " + matcher.regionStart() + " and " + matcher.regionEnd()); 
     String segText = matcher.group(0); // as well tried it with group(1) 
     textsegments += segText + "..."; 
    } 

    return textsegments; 
} 

분명히이 문제는 내 정규 표현식 내에 있지만 분명히 잘못되었습니다.

+0

당신이 표현에서 공백 문자에 대한 조항을 만든 것이 일반적으로 사용하는 것, 보이지 않는'\ s' 당신이'\ b'을 가지고 있고 그것 앞/뒤에있는 문자 클래스들 내에있는 곳에서 ...''((? : [\ w '\ .-] + \ s) {0, "+ wordsBefore + "})"'와 후에 비슷합니다 ... – abiessu

답변

3

귀하의 정규식은 기본적으로 괜찮지 만, 자바에서 탈출하는 데 필요한 \b :

"((?:[a-zA-Z'-]+[^a-zA-Z'-]+){0,5}\\b)needle(\\b(?:[^a-zA-Z'-]+[a-zA-Z'-]+){0,5})" 
+0

어쩌면 뭔가 빠졌지 만'\\ b'가 실제로 공백을 차지합니까? 나는 또한 '\\ s' 선물이 있어야한다고 생각했다 ... – abiessu

+0

\ b는 단어 경계 메타 문자이므로 공백보다 조금 더 일치한다. – wvdz

+0

그래, 그렇지만 단어 사이의 분리마다 두 개의 경계가 있어야하지 않습니까? '\\ b'는 두 단어 사이의 가능한 모든 공백 문자와 실제로 일치하지 않습니다. "공백 문자 일치"로 지정 되었기 때문에? – abiessu