java - 查找匹配文本中的单词索引
问题描述
我正在使用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,在一个数组或其他东西中。
解决方案
这是一种方法。
- 找到短语的索引并获取到该点的句子的子字符串。
- 然后使用 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);
推荐阅读
- vim - 检测缓冲区是否在状态行的非活动窗口中
- firefox - 如何从 web 扩展打开 Firefox 的“页面信息”模式
- c# - .net核心注入中的Unity风格命名服务注册?
- class - 结构成员名称是否比我使用继承的类成员使用更多内存?
- php - 带有 Laravel、Passport 和客户端凭据的私有推送通道授予客户端
- google-analytics - 分析报告 URL 中的唯一字符串是什么?
- xamarin - 如何使用 Xamarin 中的 NSDraggingInfo.EnumerateDraggingItems?
- jquery - 重置 .off() 方法
- r - 输出列表输入就绪,如 datapasta::dpasta
- excel - Excel 公式命名范围更改 - 2020 年 1 月更新