【问题标题】:How to get the positions of all matches in a String?如何获取字符串中所有匹配项的位置?
【发布时间】:2012-10-30 21:10:55
【问题描述】:

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

我想到了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;
}

此方法返回文档中所有出现的查询的列表,每一个都有其位置。

您能否建议任何更轻松、更快捷的方法来完成这项任务。

谢谢

【问题讨论】:

标签: java string match


【解决方案1】:

您的第一种方法是个好主意,但 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());
}

位置将保存比赛的所有开始位置。

【讨论】:

  • 您需要正则表达式转义查询(作为参数给出)以获取其模式。 +1,好方法。
  • 我的代码中的索引是针对单词的,因为我用空格标记了文档并循环遍历它以找到匹配项。您的方法给出了单词首字母的索引,而不是单词的位置。可以用正则表达式代替索引来查找单词的位置吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-06
  • 2011-02-06
  • 2019-05-31
  • 2022-07-16
  • 1970-01-01
  • 2020-06-23
相关资源
最近更新 更多