私はテキスト文書とクエリを持っています(クエリは複数の単語になる可能性があります)。私は、ドキュメント内のすべてのクエリの出現位置を探したい。String内のすべての一致の位置を取得する方法は?
私は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;
}
このメソッドは、ドキュメント内のクエリのすべての出現のリストを、それぞれの位置とともに返します。
このタスクを達成するための簡単で迅速な方法をお考えください。
おかげ
これは次のように役立ちます。['String#indexOf(String、int)'](http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#indexOf%28java。 lang.String、%20int%29) –