【问题标题】:How to find index of whole word in string in java如何在java中查找字符串中整个单词的索引
【发布时间】:2017-07-26 03:57:02
【问题描述】:

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

“古代手稿,另一种将句子分成的意思 段落是一个换行符(换行符),后跟一个首字母 下一段的开头。首字母是超大资本 字母,有时超出文本边缘。这种风格可以 例如,在原始的古英语手稿中可以看到 贝奥武夫。 Outdenting 仍然用于英文排版,但不是 通常。[4]现代英文排版通常表明一种新的 首行缩进段落"); "

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

谁能给出一个想法如何在java中做到这一点。 提前致谢。

【问题讨论】:

标签: java string indexof lastindexof


【解决方案1】:

您可以使用带有word boundaries character 的正则表达式:

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);

【讨论】:

  • 这适用于普通字符串,但如果我的字符串是“(或”它会因“线程中的异常“main”java.util.regex.PatternSyntaxException:索引 13 附近的未封闭组而失败)
  • 我的搜索字符串可能包含也可能不包含(或)
  • @RaviGodara 你可以使用:Matcher m = Pattern.compile("\\b" + Pattern.quote("paragraph") + "($| )").matcher(text);
  • 让它变得简单一些如果我的字符串是 String text = "paragraph paragraphs paragraph. (paragraph paragraph)";我只期待 0。当我搜索“(段落”时,我只期待“(段落”)的索引。谢谢。
  • @RaviGodara 试试看:String mySearchString = "(paragraph"; Matcher m = Pattern.compile("(^| )" + Pattern.quote(mySearchString) + "($| )").matcher(text);
猜你喜欢
  • 1970-01-01
  • 2011-07-02
  • 2018-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-16
  • 1970-01-01
  • 2013-09-15
相关资源
最近更新 更多