2012-11-10 5 views
5

텍스트 문서와 쿼리가 있습니다 (쿼리는 둘 이상의 단어 일 수 있음). 문서에서 쿼리의 모든 발생 위치를 찾고 싶습니다.문자열에서 모든 일치 항목의 위치를 ​​얻는 방법은 무엇입니까?

나는 documentText.indexOf(query)을 생각하거나 정규 표현식을 사용했지만 작동하지 못했습니다.

나는 다음과 같은 방법으로 끝낼 :

는 첫째, 나는 그런 QueryOccurrence

public class QueryOccurrence implements Serializable{ 
    public QueryOccurrence(){} 
    private int start; 
    private int end;  

    public QueryOccurrence(int nameStart,int nameEnd,String nameText){ 
    start=nameStart; 
    end=nameEnd;   
    } 

    public int getStart(){ 
    return start; 
    } 

    public int getEnd(){ 
    return end; 
    } 

    public void SetStart(int i){ 
    start=i; 
    } 

    public void SetEnd(int i){ 
    end=i; 
    } 
} 

라는 데이터 유형을 만들 수있다, 나는 다음과 같은 방법이 데이터 유형을 사용하고 있습니다 :

public static List<QueryOccurrence>FindQueryPositions(String documentText, String query){ 

    // Normalize do the following: lower case, trim, and remove punctuation 
    String normalizedQuery = Normalize.Normalize(query); 
    String normalizedDocument = Normalize.Normalize(documentText); 

    String[] documentWords = normalizedDocument.split(" ");;    
    String[] queryArray = normalizedQuery.split(" "); 


    List<QueryOccurrence> foundQueries = new ArrayList(); 
    QueryOccurrence foundQuery = new QueryOccurrence(); 

    int index = 0; 

    for (String word : documentWords) {    

     if (word.equals(queryArray[0])){ 
      foundQuery.SetStart(index); 
     } 

     if (word.equals(queryArray[queryArray.length-1])){ 
      foundQuery.SetEnd(index); 
      if((foundQuery.End()-foundQuery.Start())+1==queryArray.length){ 

       //add the found query to the list 
       foundQueries.add(foundQuery); 
       //flush the foundQuery variable to use it again 
       foundQuery= new QueryOccurrence(); 
      } 
     } 

     index++; 
    } 
    return foundQueries; 
} 

이 메서드는 문서에서 쿼리의 모든 항목 목록을 위치와 함께 반환합니다.

이 작업을 수행하는 더 쉽고 빠른 방법을 제안 해주세요.

감사

+0

이렇게하면 도움이됩니다. ['String # indexOf (String, int)'] (http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#indexOf%28java. lang.String, % 20int % 29) –

답변

12

첫 번째 접근 방식은 좋은 생각하지만, 경우 String.indexOf는 정규 표현식을 지원하지 않습니다.

List<Integer> positions = new ArrayList(); 
Pattern p = Pattern.compile(queryPattern); // insert your pattern here 
Matcher m = p.matcher(documentText); 
while (m.find()) { 
    positions.add(m.start()); 
} 

위치가 일치 모든 시작 위치를 개최합니다 경우 다음과 같이

유사한 접근 방식을 사용하지만, 두 단계 방법의 또 다른 쉬운 방법이다.

+0

패턴을 얻기 위해 쿼리를 정규식 이스케이프 (매개 변수로 제공)해야합니다. +1, 좋은 접근 방식. –

+0

내 코드의 색인은 공백으로 문서를 토큰 화하고 일치하는 항목을 찾기 위해 반복합니다. 귀하의 접근 방식은 단어의 첫 글자의 색인이 아니라 단어의 위치를 ​​제공합니다. Regex를 사용하여 색인 대신 단어의 위치를 ​​찾을 수 있습니다. – user692704

관련 문제