首页 > 解决方案 > 查找匹配文本中的单词索引

问题描述

我正在使用Matcher在一个句子中查找一个短语,但我还想在找到的短语中找到每个单词的索引。我的意思是想象一个句子被每个单词索引:

This is my wonderful sentence
0    1  2  3         4

它们将按上述方式编入索引。但是,我只需要找到短语本身,而不是句子中其他地方的短语中的单个单词。

I know this sentence repeats but you know that it doesn't
0 1    2    3        4       5   6   7    8    9  10

如果我匹配短语but you know我想得到匹配的单词的索引,但我不想为know靠近开头的单词返回索引 1,我只想返回 5、6 和 7。我想不出在我将短语与此代码匹配后,有什么好的方法可以做到这一点:

String line = "I know this sentence repeats but you know that it doesn't";

final Matcher match = Pattern.compile("but you know").matcher(line);
if (match.find()) 
    System.out.println(match.group(0));

所以要清楚,然后我想要这个匹配短语中的索引号 5、6 和 7,在一个数组或其他东西中。

标签: javamatcher

解决方案


这是一种方法。

  • 找到短语的索引并获取到该点的句子的子字符串。
  • 然后使用 split 计算子字符串中的单词。数组的长度将是短语第一个单词的起始索引,除非indexOfPhrase == 0. 那么它将是0。
  • 然后拆分短语得到每个单词,递增初始子字符串的前一个单词索引。
String sentence =
        "I know this sentence repeats but you know that it doesn't";

String phrase = "but you know";

int indexOfPhrase = sentence.indexOf(phrase);

String[] temp = sentence.substring(0, indexOfPhrase).trim().split("\\s+");
int firstIndex = indexOfPhrase == 0 ? 0 : temp.length;

int start = firstIndex;
for (String word : phrase.split("\\s+")) {
    System.out.printf("%8s : %d%n", word,start++);
}

印刷

     but : 5
     you : 6
    know : 7

要将值放入数组中,您可以执行以下操作:

int[] indices = new int[phrase.split("\\s+").length]; 
Arrays.setAll(indices, i-> firstIndex+i);

推荐阅读