我有一个字符串,这是一个html页面的完整内容,我正在尝试查找</table>
的第二次出现的索引。有没有人对如何做到这一点有什么建议?
发布于 2011-04-15 22:59:06
这是一个有趣的镜头;)
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;
}
发布于 2013-01-16 19:11:00
使用indexOf对@BasVanDenBroek's answer进行了推广:
public static int nthIndexOf(String source, String sought, int n) {
int index = source.indexOf(sought);
if (index == -1) return -1;
for (int i = 1; i < n; i++) {
index = source.indexOf(sought, index + 1);
if (index == -1) return -1;
}
return index;
}
快速测试:
public static void main(String[] args) throws InterruptedException {
System.out.println(nthIndexOf("abc abc abc", "abc", 1));
System.out.println(nthIndexOf("abc abc abc", "abc", 2));
System.out.println(nthIndexOf("abcabcabc", "abc", 2));
System.out.println(nthIndexOf("abcabcabc", "abc", 3));
System.out.println(nthIndexOf("abc abc abc", "abc", 3));
System.out.println(nthIndexOf("abc abc defasabc", "abc", 3));
System.out.println(nthIndexOf("abc abc defasabc", "abc", 4));
}
发布于 2012-08-01 04:48:41
查找字符串的第N个匹配项的另一个好选择是使用Apache Commons中的StringUtils.ordinalIndexOf():
StringUtils.ordinalIndexOf("aabaabaa", "b", 2) == 5
https://stackoverflow.com/questions/5678152
复制相似问题