0

我想找出给定字符串中整个单词的所有起始索引。假设我在下面给出了一个字符串。

“一个古老的手稿,另一种将句子分成段落的方法是换行符(换行符),然后在下一段的开头加上一个首字母。首字母是一个超大的大写字母,有时超出文本的边缘。这种风格可以例如,在 Beowulf 的古英语原稿中可以看到。虽然不常见,但在英文排版中仍然使用缩进。[4] 现代英文排版通常通过缩进第一行来表示新段落");"

我只想找出“段落”的起始索引。其中不应包括“段落”、“段落”。

任何人都可以给出一个想法如何在java中做到这一点。提前致谢。

4

1 回答 1

3

您可以使用带有单词边界字符的正则表达式:

String text = "an ancient manuscripts, another means to divide sentences into paragraphs was a line break (newline) followed by an initial at the beginning of the next paragraph. An initial is an oversize capital letter, sometimes outdented beyond the margin of text. This style can be seen, for example, in the original Old English manuscript of Beowulf. Outdenting is still used in English typography, though not commonly.[4] Modern English typography usually indicates a new paragraph by indenting the first line";

Matcher m = Pattern.compile("\\bparagraph\\b").matcher(text);
while (m.find()) {
    System.out.println("Matching at: " + m.start());
}

如果你不想要“段落”。(“段落”后跟一个点),你可以试试

Matcher m = Pattern.compile("\\bparagraph($| )").matcher(text);

这意味着段落后跟空格或行尾。

如果您要查找的字符串可以包含特殊字符(如“(”),您可以使用Pattern.quote()它来转义它:

String mySearchString = "paragraph";
Matcher m = Pattern.compile("\\b" + Pattern.quote(mySearchString) + "($| )").matcher(text);
于 2017-03-06T10:22:59.227 回答