How to find index of whole word in string in java

ぃ、小莉子 提交于 2019-11-29 17:42:58

You can use a regexp with 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());
}

If you don't want "paragraph." ("paragraph" followed by a dot), you can try

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

which means paragraph followed by a space or a end-of-line.

If the String you are looking for can include special characters (like "("), you can use Pattern.quote() to escape it:

String mySearchString = "paragraph";
Matcher m = Pattern.compile("\\b" + Pattern.quote(mySearchString) + "($| )").matcher(text);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!