在Java字符串中找到子字符串的第n次出现? [英] find the nth occurence of a substring in a string in java?

查看:54
本文介绍了在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;
}

这篇关于在Java字符串中找到子字符串的第n次出现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆