java怎么匹配全部_java – 如何获取String中所有匹配的位置?

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

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

我最终得到以下方法:

首先,我创建了一个名为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;

}

此方法返回文档中每个查询的所有出现的列表及其位置.

你能否提出更轻松,更快捷的方法来完成这项任务.

谢谢

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值