【发布时间】:2015-12-03 20:36:33
【问题描述】:
我需要获取要搜索的数组中元素的索引:
String[] items = {"One:10.1.22.33", "Two:10.1.21.23", "Three:10.1.21.33", "Four:10.1.21.23", "Five:10.1.22.23"};
String q = "Two"; //need to find index of element starting with sub-sting "Two"
我尝试过的
试一试
String temp = "^"+q;
System.out.println(Arrays.asList(items).indexOf(temp));
Try-2
items[i].matches(temp)
for(int i=0;i<items.length;i++) {
if(items[i].matches(temp)) System.out.println(i);
}
两者都没有按预期工作。
【问题讨论】:
-
matches尝试匹配整个字符串。如果您想使用matches,则必须使用"^" + q + ".*"或类似的东西。 (您可能还想将q包装在Pattern.quote中。) -
感谢它为 items[i].matches 工作,但不适用于 .indexof
-
什么意思?如果您使用
temp = "Two.*",则应打印1。不是吗? (String.indexOf只能用于String,而不是字符串列表。) -
等等,为什么不用多维数组呢?
-
@aioobe 谢谢伟大的信息
标签: java arrays regex substring indexof