Ho un documento di testo e una query (la query potrebbe essere più di una parola). Voglio trovare la posizione di tutte le occorrenze della query nel documento.Come ottenere le posizioni di tutte le partite in una stringa?
Ho pensato allo documentText.indexOf(query)
o utilizzando l'espressione regolare ma non riuscivo a farlo funzionare.
io alla fine con il seguente metodo:
In primo luogo, devo creare un tipo di dati chiamato 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;
}
}
Poi, ho usato questo tipo di dati nel seguente metodo:
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;
}
Questo metodo restituisce un elenco di tutte le occorrenze della query nel documento ciascuna con la sua posizione.
Potrebbe suggerire un modo più semplice e veloce per eseguire questa operazione.
Grazie
Questo dovrebbe aiutare: ['String # indexOf (String, int)'] (http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#indexOf%28java. lang.String,% 20int% 29) –