如何获取String中所有匹配的位置?

我有一个文本文档和一个查询(查询可能不止一个单词)。 我想在文档中找到所有出现的查询的位置。

我想到了documentText.indexOf(query)或使用正则表达式,但我无法使其工作。

我最终得到以下方法:

首先,我创建了一个名为QueryOccurrence的dataType

 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 ListFindQueryPositions(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 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不支持正则表达式。

使用类似方法的另一种更简单的方法,但是采用两步法,如下:

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

位置将保持比赛的所有起始位置。