You would be better off using startsWith(String prefix)as follows:
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";
for (int i = 0; i < items.length; i++) {
if (items[i].startsWith(q)) {
System.out.println(i);
}
}
Your first attempt does not work, because you are trying to get the String index ^Twoinside your list, but indexOf(String str)not accepting a regular expression.
Your second attempt does not work, because it matches(String regex)works in the entire line, and not just in the beginning.
Java 8, , , "Two", -1, .
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";
int index = IntStream.range(0, items.length).filter(i -> items[i].startsWith(q)).findFirst().orElse(-1);