在Java字符串中找到子字符串的第n次出现?
问题描述:
我有一个字符串,它是html页面的完整内容,我正在尝试查找</table>
的第二次出现的索引.有人对如何实现这一目标有什么建议吗?
I have a string that is the complete content of an html page and I am trying to find the index of 2nd occurence of </table>
. Does anyone have any suggestions on how to achieve this?
答
在这里很有趣;)
public static int findNthIndexOf (String str, String needle, int occurence)
throws IndexOutOfBoundsException {
int index = -1;
Pattern p = Pattern.compile(needle, Pattern.MULTILINE);
Matcher m = p.matcher(str);
while(m.find()) {
if (--occurence == 0) {
index = m.start();
break;
}
}
if (index < 0) throw new IndexOutOfBoundsException();
return index;
}